在单个查询中按多个日期范围聚合列

时间:2014-04-25 23:14:30

标签: mysql sql

我有一个包含5列的MySQL表:

Device | Name | Date | Source | Income

设备名称来源都不是唯一的。

我正在尝试编写SQL以获取以下内容:

Device | Name | Source | Income (for last 3 days) | Income (for last 9 days) | Income (for last 12 days)

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

您可以通过SUM()语句获得条件CASE

SELECT Device
      ,Name
      ,Source
      ,SUM(CASE WHEN date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 3 day) AND UNIX_TIMESTAMP(NOW()) THEN Income END) AS Last_3_Days
      ,SUM(CASE WHEN date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 9 day) AND UNIX_TIMESTAMP(NOW()) THEN Income END) AS Last_9_Days
FROM YourTable
GROUP BY Device
        ,Name
        ,Source   

答案 1 :(得分:0)

SELECT COUNT(*) as total_l3d FROM table WHERE DATEDIFF(Date, NOW()) <= 3
UNION
SELECT COUNT(*) as total_l9d FROM table WHERE DATEDIFF(Date, NOW()) <= 9
UNION
SELECT COUNT(*) as total_l12d FROM table WHERE DATEDIFF(Date, NOW()) <= 12