Mysql 如何使用数据计数按月份和年份分组

Mysql 如何使用数据计数按月份和年份分组,mysql,Mysql,我有一个包含如下数据的表: id | question | pub_date 1 | qeustion1| 2012-12-03 2 | qeustion2| 2012-12-06 3 | qeustion3| 2012-11-03 4 | qeustion4| 2011-12-03 我想要一个像这样的输出: 它应根据年、月结果计数和描述顺序对记录进行计数,并应显示每行数据 就我而言: 年份:2012年有3项记录 月份:2012年12月有2项记录 年份:2011年有1项记录 月份

我有一个包含如下数据的表:

id | question | pub_date
1  | qeustion1| 2012-12-03
2  | qeustion2| 2012-12-06 
3  | qeustion3| 2012-11-03 
4  | qeustion4| 2011-12-03
我想要一个像这样的输出: 它应根据年、月结果计数和描述顺序对记录进行计数,并应显示每行数据

就我而言:

  • 年份:2012年有3项记录
  • 月份:2012年12月有2项记录
  • 年份:2011年有1项记录
  • 月份:2011年12月有1项记录
我试过这个:

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
我需要显示这样的数据请参见

博客存档部分尝试以下操作:

select count(id)
from mytable
group by year(pub_date), month(pub_date)
order by year(pub_date) desc, month(pub_date) desc
如果您想知道有哪些月份和年份,请使用:

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
从月份和年份中获取数据

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)

我假设您想要的结果是:

2012           3
2012 12        2
2012 11        1
2011           1
2011 11        1
您可以通过对两个聚合查询使用
union
来实现这一点:

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)

这将只返回计数而不是数据。其行为与我的查询完全相同。我也需要数据。你看到我提到的链接了吗?你说的数据是什么意思?我更新了第二个查询,检查这是否是您需要的。我的意思是,如果我有两行,同一年,它将在一行中显示计数2,而不是两行。我想我明白了。这是一个你需要的更复杂的查询,对吗?基本上,你需要在PHP或其他代码中的两个查询(一个用于年,一个用于月)中执行类似的操作。也许您可以从示例数据中显示您想要的输出