按年龄,3个月,6个月,9个月和12个月对组进行Mysql查询

时间:2015-05-06 14:48:38

标签: mysql sql

+------+------------+ 
| cost | date       |
+------+------------+ 
|   44 | 2015-04-30 | 
|   39 | 2015-04-31 | 
|   18 | 2015-04-01 | 
|   71 | 2015-01-02 | 
|   69 | 2014-12-03 | 
|   62 | 2014-12-04 | 
|   89 | 2014-08-05 | 
|   72 | 2014-08-06 | 
|   46 | 2014-05-07 | 
|   23 | 2014-05-08 |
+------+------------+

从上表中,我想写一个查询,从现在开始分别在3个月,6个月9个月和1年前分摊总成本。

我可以知道我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在case

中添加group by语句
select (case when date >= date_sub(now(), interval 3 month) then '3month'
             when date >= date_sub(now(), interval 6 month) then '6month'
             when date >= date_sub(now(), interval 9 month) then '9month'
             when date >= date_sub(now(), interval 12 month) then '12month'
        end) as grp, sum(cost) as sumcost
from table t
where date >= date_sub(now(), interval 12 month)
group by grp;