如何正确总结datetime(end_date和begin date之间的区别) - mysql
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何正确总结datetime(end_date和begin date之间的区别) - mysql相关的知识,希望对你有一定的参考价值。
我在mysql中使用。我创建了表“Sikcness”,我添加了一条记录:
+--------+---------+---------+-------------+--------+----------+
| Id_SICK|ID_WORKER| BEGIN_DATE | END_DATE |
+--------+---------+---------+----------+------------+---------+
| 1 | 1 |2019-03-18 07:00:00 |2019-03-20 15:00:00 |
+--------+---------+--------+------------+----------+----------+
然后我想用命令总结时间(结束日期列和开始日期列之间的时间差):
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上尝试此查询
另一答案
所以,你需要像这样计算它:
- 疾病第一天的小时数
- 疾病最后一天的小时数
- 疾病天数乘以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。
以上是关于如何正确总结datetime(end_date和begin date之间的区别) - mysql的主要内容,如果未能解决你的问题,请参考以下文章
powerbuilder里面如何把editmask中输入的字符串类型如何转换成datetime啊用来比较和datetime类型的大小 !