+------+------------+
| 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 年前的总成本。
我该怎么做?
最佳答案
您可以在group by
中放置case
语句:
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;
关于MySQL查询按年龄、3个月、6个月、9个月和12个月分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30080179/