+------+------------+
| 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年前分摊总成本。
我可以知道我该怎么做?
答案 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;