我有一个包含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)
这样做的最佳方式是什么?
答案 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