我的表格中有这些数据,如果我的查询来自end_time
和 +----+---------------------+---------------------+
| id | start_time | end_time |
+----+---------------------+---------------------+
| 3 | 2015-11-09 04:00:00 | 2015-11-09 20:00:00 |
| 6 | 2015-11-09 04:00:00 | 2015-11-09 10:00:00 |
| 7 | 2015-11-09 06:00:00 | 2015-11-09 17:00:00 |
| 8 | 2015-11-09 15:00:00 | 2015-11-09 20:00:00 |
| 9 | 2015-11-09 01:00:00 | 2015-11-09 05:00:00 |
+----+---------------------+---------------------+
06:00 17:00
| |
| |
1. S------E | |
| |
| |
2. S------E |
| |
| |
3. | S------E |
| |
| |
4. S----------------------E
| |
| |
5. | S------E
| |
| |
6. | | S------E
时间'06:00:00' - '17:00:00,我想计算小时和分钟'并计算不在'06:00:00'到'17:00:00'
注意:start_time('06:00:00')和end_time('17:00:00')不是静态的,只是在表格中输入。
这是我表格中的数据。
SELECT id,Time_to_sec(Timediff(Least(Time(end_time), '17:00:00'),
Least(Time(start_time), '06:00:00'))) / 3600 AS
outside
FROM activelogs
WHERE (Time(start_time) < '06:00:00' OR Time(end_time) > '17:00:00')
AND Date(start_time) >= '2015-11-01'
AND Date(end_time) <= '2015-11-20'
这是我的尝试。
+----+---------+
| id | outside |
+----+---------+
| 3 | 5 |
| 6 | 2 |
| 8 | 3 |
| 9 | 4 |
+----+---------+
预期输出
ABug.symbol
答案 0 :(得分:4)
如果我理解正确,您希望在特定边界之外花费的时间。让我们在几秒钟内完成计算。您可以将其转换为您喜欢的任何内容:
SELECT id,
(greatest(time_to_sec(least(time(end_time), '06:00:00')) - time_to_sec(start_time), 0) +
greatest(time_to_sec(end_time) - time_to_sec(greatest(time(start_time), '17:00:00')), 0)
) as outside_seconds
FROM activelogs
WHERE Date(start_time) >= '2015-11-01' AND Date(end_time) <= '2015-11-20';
此计算有两个组成部分。第一个是上午6点之前的时段,第二个是下午5点之后的时段。
要消除id = 7,您可以修改where
子句:
WHERE Date(start_time) >= '2015-11-01' AND Date(end_time) <= '2015-11-20' AND
(Time(start_time) < '06:00:00' OR Time(end_time) > '17:00:00')
答案 1 :(得分:-1)
这也是诀窍
SELECT
id,
CASE
WHEN (HOUR(start_time) < 6) AND (HOUR(end_time) > 17) THEN
(6 - HOUR(start_time) + HOUR(end_time) -17)
WHEN (HOUR(start_time) between 6 AND 17) AND (HOUR(end_time) > 17) THEN
(HOUR(end_time) -17)
WHEN (HOUR(start_time) < 6) AND (HOUR(end_time) between 6 AND 17) THEN
(6 - HOUR(start_time))
WHEN (HOUR(start_time) > 17) AND (HOUR(end_time) > 17) THEN
(HOUR(end_time) - HOUR(start_time))
WHEN (HOUR(start_time) < 6) AND (HOUR(end_time) < 6) THEN
(HOUR(end_time) - HOUR(start_time))
ELSE 0
END as outside
FROM activelogs