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条记录
  • 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

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

最佳答案

我假设你想要的结果是这样的:

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)

关于mysql - 如何根据数据计数按月和年进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13744136/

相关文章:

php - SQLSTATE[23000] : Integrity constraint violation: in Laravel 5. 2

mysql - SQL 更新语句不适用于 281 条记录

mysql - BEFORE UPDATE 触发器阻止所有更新

mysql - 数据库方法 - 冗余数据

php - 同时存在createdBy和updatedBy时正确加入users表

Php Mysql 插入多个外键

MySQL:返回列中最后5位数字的最大值

php - 使用 android volley 和 php 将波斯语值发布到 mysql

mysql - 导轨 : Mysql query returning null

php - 使用 php 脚本导入 Mysql xlsx 文件 大文件(以 MB 为单位)