1

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

 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”;有什么办法吗?

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

4

2 回答 2

0

这只是 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;
于 2013-06-12T03:06:37.263 回答
0

您可以利用该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`)

现场样品

于 2013-06-12T03:11:33.800 回答