如何正确总结日期时间(end_date 和 begin_date 之间的差异)- mysql

How to sumarize corectly datetime (difference between end_date and begin_date) - mysql

我在 mysql 中使用。我创建了 table "Sikcness" 并添加了一条记录:

+--------+---------+---------+-------------+--------+----------+
| Id_SICK|ID_WORKER| BEGIN_DATE          | END_DATE            |
+--------+---------+---------+----------+------------+---------+
| 1      |   1     |2019-03-18 07:00:00  |2019-03-20 15:00:00  |  
+--------+---------+--------+------------+----------+----------+  

然后我想通过命令及时总结(End_date列和begin_date列之间的时间差):

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(Sickness.END_DATE) - TIME_TO_SEC(Sickness.BEGIN_DATE))) AS 'SICKNESS TIME' FROM Sickness WHERE ID_WORKER = 1

但我只有那个结果(这是不正确的):

SICKNESS TIME
08:00:00

该命令应该这样计算:

+---------+-------------+--------+----------+
| BEGIN_DATE          | END_DATE            |
+---------+----------+------------+---------+
|2019-03-18 07:00:00  |2019-03-18 15:00:00  |  
+--------+------------+----------+----------+  
|2019-03-19 07:00:00  |2019-03-19 15:00:00  |  
+--------+------------+----------+----------+  
|2019-03-20 07:00:00  |2019-03-20 15:00:00  |  
+--------+------------+----------+----------+ 

那么应该是:

SICKNESS TIME
24:00:00

我应该写什么样的 mysql 查询?有任何想法吗?问候。

小时差乘以天差:

mysql> SELECT SEC_TO_TIME(SUM((DATEDIFF(end_date, begin_date) + 1) * (TIME_TO_SEC(END_DATE) - TIME_TO_SEC(BEGIN_DATE)))) AS 'SICKNESS TIME' FROM Sickness WHERE ID_WORKER = 1;
+---------------+
| SICKNESS TIME |
+---------------+
| 24:00:00      |
+---------------+
1 row in set (0.00 sec)

TIME_FORMAT 的另一个查询:

mysql> select time_format(SUM((datediff(end_date, begin_date) + 1) * (time(end_date) - time(begin_date))), '%H:%i:%s') as 'SICKNESS TIME' from Sickness where id_worker = 1;
+---------------+
| SICKNESS TIME |
+---------------+
| 24:00:00      |
+---------------+
1 row in set (0.00 sec)

您可以在 SQL Fiddle

上尝试此查询

所以,你需要这样计算:

  1. 生病第一天的小时数
  2. 生病最后一天的小时数
  3. 生病天数乘以8(即工作小时数)

完成后,您需要将这些相加以获得结果,例如

SELECT
TIMESTAMPDIFF(HOUR, begin_date, CONCAT(DATE(begin_date), ' 15:00:00')) +
(TIMESTAMPDIFF(DAY, begin_date, end_date) - 1) * 8 +
TIMESTAMPDIFF(HOUR, CONCAT(DATE(end_date), ' 07:00:00'), end_date) AS time 
FROM test
WHERE worker = 1;

这是SQL Fiddle.