计算来自多年和逐月的数据

时间:2013-06-12 02:41:14

标签: mysql

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

 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,我怎样才能正确排序?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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`)

Live Sample