我在写一个管理工作时间的软件。因为每一天都有不同的活动。
我想把过去7天每个工人的工作时间都提取出来。
示例行
+----+------------+-------+----------+----------+
| id | date | order | operator | duration |
+----+------------+-------+----------+----------+
| 37 | 2016-06-12 | 27 | 1 | 180 |
| 38 | 2016-06-12 | 28 | 3 | 390 |
| 39 | 2016-06-12 | 27 | 1 | 480 |
| 40 | 2016-06-04 | 21 | 2 | 120 |
| 41 | 2016-05-07 | 27 | 1 | 90 |
| 42 | 2016-06-07 | 27 | 1 | 150 |
+----+------------+-------+----------+----------+
询问
SELECT SUM(`duration`) as `hours_per_day`
FROM `sheets`
WHERE `operator` = 1 AND `date` = DATE_ADD(CURDATE(), INTERVAL -7 DAY)
ORDER BY `date` DESC
预期结果:
+------------------------+--------+--------+--------+--------+--------+--------+--------+
| Operator: Avareage Joe |
+------------------------+--------+--------+--------+--------+--------+--------+--------+
| Day: | 01 jul | 02 jul | 03 jul | O4 jul | 05 jul | 06 jul | 07 jul |
| Hours: | 8 | 7 | 9 | 8 | 9 | 8 | 6 |
+------------------------+--------+--------+--------+--------+--------+--------+--------+
最佳答案
SELECT
CURDATE(),
SUM(CASE WHEN CURDATE() = `date` THEN `duration` ELSE 0 END) as today ,
SUM(CASE WHEN CURDATE() - INTERVAL 1 DAY = `date` THEN `duration` ELSE 0 END) as yesterday,
SUM(CASE WHEN CURDATE() - INTERVAL 2 DAY = `date` THEN `duration` ELSE 0 END) as `today - 2`,
SUM(CASE WHEN CURDATE() - INTERVAL 3 DAY = `date` THEN `duration` ELSE 0 END) as `today - 3`,
SUM(CASE WHEN CURDATE() - INTERVAL 4 DAY = `date` THEN `duration` ELSE 0 END) as `today - 4`,
SUM(CASE WHEN CURDATE() - INTERVAL 5 DAY = `date` THEN `duration` ELSE 0 END) as `today - 5`,
SUM(CASE WHEN CURDATE() - INTERVAL 6 DAY = `date` THEN `duration` ELSE 0 END) as `today - 6`
FROM `work`
where operator = 1
输出