MySQL查询按年龄、3个月、6个月、9个月和12个月分组

标签 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 年前的总成本。

我该怎么做?

最佳答案

您可以在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/

相关文章:

python - 使用 Python 进行 SQLite 查询

MySQL 超慢内连接与 group by

mysql - 多个表的减法 - sql

php - 如何连接两个截然不同的mysql表,并同时按两列排序?

mysql - 从两个不同的表插入到一个表中

查询中的 MySQL NOW() + 14 或 CURDATE() + 14

sql - 如何避免 SQL 中的重复子查询 JOIN?

php - 遍历数据库并使用 foreach 循环更新字段

java - 如何解决此通信链路故障?

mysql - 为什么 MySQL 5.7 Even Scheduler START 日期时间与 CREATE/ALTER EVENT START 时间不匹配?