Mysql 查询按年龄、3 个月、6 个月、9 个月和 12 个月分组
Mysql query to group by age, 3 months, 6 months, 9 months and 12 months
+------+------------+
| 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 |
+------+------------+
根据上面的table,我想写一个查询,从现在开始,将总费用分为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;
+------+------------+
| 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 |
+------+------------+
根据上面的table,我想写一个查询,从现在开始,将总费用分为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;