【问题标题】:count data from multiple year and group by month计算来自多年和按月分组的数据
【发布时间】:2013-06-12 02:41:14
【问题描述】:

我要制作图表,这是我的表格;

 mrp
+------------+
| date       |
+------------+
| 2011-10-xx |
| 2011-12-xx |
| 2012-01-xx |
| 2012-05-xx |
| 2013-01-xx |
| 2013-02-xx |
+------------+

我想按月分组统计过去 3 年的数据,这就是我想要实现的目标;

+--------+--------+--------+--------+
| quarty | 2011   | 2012   | 2013   |
+--------+--------+--------+--------+
|jan-mar | 0      | 1      | 2      |
|apr-jun | 0      | 1      | 0      |
|jul-sept| 0      | 0      | 0      |
|oct-dec | 2      | 0      | 0      |
+--------+--------+--------+--------+

我试过了;

select case when month(date) between 1 and 3 then 'Jan-Mar'
when month(date) between 4 and 6 then 'Apr-Jun'
when month(date) between 7 and 9 then 'Jul-Sept'
else 'Oct-Dec' end 'quarty',
SUM(year(date) = 2011) AS `2011`,
SUM(year(date) = 2012) AS `2012`,
SUM(year(date) = 2013) AS `2013`
from `mrp` where year(date) >= 2011
group by 'quarty'

但不知何故,它只在 2011 年、2012 年和 2013 年显示 'Oct-Dec';有什么办法吗?

注意:我已经找到另一个查询如何显示 all month仅在一年内,我无法正确排序,它首先显示 apr-jun ,然后是 jan-mar、jul-sept 和 oct-dec,如何正确排序?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以利用QUARTER 功能为您完成工作。

    SELECT CASE WHEN QUARTER(`date`) = 1 THEN 'Jan-Mar'
                WHEN QUARTER(`date`) = 2 THEN 'Apr-Jun'
                WHEN QUARTER(`date`) = 3 THEN 'Jul-Sep'
                WHEN QUARTER(`date`) = 4 THEN 'Oct-Dec'
           END AS `Quarty`,
           SUM(year(`date`) = 2011) AS `2011`,
           SUM(year(`date`) = 2012) AS `2012`,
           SUM(year(`date`) = 2013) AS `2013`
    FROM `mrp`
    WHERE year(`date`) >= 2011
    GROUP BY QUARTER(`date`)
    

    Live Sample

    【讨论】:

      【解决方案2】:

      这是 2011 年的,但您可以自己添加 2012 年和 2013 年的表格

      select
      case
        when monthvalue=1 then 'Jan-Mar'
        when monthvalue=2 then 'Apr-Jun'
        when monthvalue=3 then 'Jul-Sep'
        when monthvalue=4 then 'Oct-Dec'
      end as period,
      t2011.x as freq2011 from
      (SELECT CEIL(MONTH(date)/3) as monthVALUE,count(*) as x
      FROM mrp
      where year(date)=2011
      GROUP BY monthVALUE) t2011;
      

      【讨论】:

        猜你喜欢
        • 2012-01-25
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        相关资源
        最近更新 更多