首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用数据计数按月和年分组?

如何使用数据计数按月和年分组?
EN

Stack Overflow用户
提问于 2012-12-06 12:59:51
回答 2查看 235关注 0票数 0

我有一张桌子上有这样的数据:

代码语言:javascript
复制
id | question | pub_date
1  | qeustion1| 2012-12-03
2  | qeustion2| 2012-12-06 
3  | qeustion3| 2012-11-03 
4  | qeustion4| 2011-12-03

我想要一个输出,比如:它应该根据年份、月份结果计数和Desc顺序来计数记录,并且还应该显示每一行数据。

就我而言:

  • 年份:2012年有3项记录
  • 月份:2012年12月份有2次记录
  • 年份:2011年有1次记录
  • 月份:2011年有12个月创1次记录。

我试过这样做:

代码语言:javascript
复制
SELECT
    EXTRACT(MONTH FROM pub_date) as month, 
    EXTRACT(YEAR FROM pub_date) as year, 
    Count(id)
FROM 
    mytable
GROUP BY 
    month,
    year
ORDER BY 
    year DESC, 
    month DESC

我需要显示这样的数据,请参阅博客存档站点部分

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-06 16:31:30

我想你想要的结果是:

代码语言:javascript
复制
2012           3
2012 12        2
2012 11        1
2011           1
2011 11        1

您可以通过在两个聚合查询上使用union来获得这个结果:

代码语言:javascript
复制
select s.*
from ((select year(pub_date) as yr, NULL as month, count(*) as cnt
       from t
       group by year(pub_date)
      ) union all
      (select year(pub_date) as yr, month(pub_date) as mon, count(*) as cnt
       from t
       group by year(pub_date), month(pub_date)
      )
     ) s
order by yr desc,
         (case when mon is null then -1 else mon end)
票数 1
EN

Stack Overflow用户

发布于 2012-12-06 13:06:10

试试这个:

代码语言:javascript
复制
select count(id)
from mytable
group by year(pub_date), month(pub_date)
order by year(pub_date) desc, month(pub_date) desc

如果您想知道有几个月和几年,请使用:

代码语言:javascript
复制
select year(pub_date) as year, month(pub_date) as month, count(id), *
from mytable
group by year(pub_date), month(pub_date)
order by year(pub_date) desc, month(pub_date) desc

获取月份和年份的数据

代码语言:javascript
复制
select year(pub_date) as year, year_count, month(pub_date) as month, count(rowid) as month_count
from mytable u
, (
select year(pub_date) as year, count(rowid) year_count
from mytable
group by year(pub_date)
) as tab
where tab.year = year(u.pub_date)
group by year(pub_date), month(pub_date)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13744136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档