按天计算工作小时数和总和

时间:2016-07-12 15:54:23

标签: mysql

我正在编写一个软件来管理工作时间。每天可能会有不同的活动。 我希望在过去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      |
+------------------------+--------+--------+--------+--------+--------+--------+--------+

2 个答案:

答案 0 :(得分:1)

让我们这样试试:

SELECT    operator, `date`, (SUM(duration) / 60) as hours_per_day
FROM      sheets
WHERE     `date` > NOW() - INTERVAL 7 DAY
GROUP BY  operator, date
ORDER BY  operator, date

首先看一下WHERE子句。我们排除了超过7天的所有内容。

然后我们使用GROUP BY获取所有剩余行并按操作符和日期对它们进行分组,因此您基本上可以获得可以使用的小子结果。

我保留了您的SUM(duration)操作,现在计算每个小子结果的总和。我刚刚添加了该部门,因为显然你需要存储分钟,而不是小时。

最后我们使用ORDER BY来确保结果看起来不是一团糟。

您的结果应如下所示:

 operator | date         | hours_per_day
 ---------------------------------------
 1        | 2016-07-01   | 4
 1        | 2016-07-02   | 6
 1        | 2016-07-03   | 6
 2        | 2016-07-01   | 8
 2        | 2016-07-02   | 7

答案 1 :(得分:1)

<强> SQL Fiddle Demo

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

<强>输出

enter image description here