我有一个表格,其中有两列包含特定事件的time_from
和time_to
。两列的类型都是TINYINT(2)。对于eaxmple
id time_from time_to
__________________________
11 8 14
18 12 17
44 20 24
有些时期重叠。我需要总结所有时间,并确保我不会重复计算重叠时间。
不幸的是,我不能改变列类型,必须使用我所拥有的。我怎么能这样做?
预期结果如下:
14 - 8 = 6
17 - 12 = 5
24-20 = 4
重叠是2小时(12 - 14)
总计:6 + 5 + 4 - 2 = 13答案 0 :(得分:3)
我假设您的time_from
和time_to
列代表1到24范围内的小时数。
修改即可。正如你澄清的那样,我假设有20个,24个有四个小时,即20,21,22,23。每个范围都不包括提到的最后一个小时:[20,24)
。
您可以使用序列表解决此问题。就是这个。 (http://sqlfiddle.com/#!9/57cf7f/4/0)
SELECT 1 seq
UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13
UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17
UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24
在MariaDB中,它是内置的:表seq_1_to_24
就是它。
像这样加入你的另一个表,你在另一个表的每一行中每小时得到一行。 (http://sqlfiddle.com/#!9/57cf7f/9/0)
SELECT seq.seq, t.*
FROM (
SELECT 1 seq UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13
UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17
UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24
) seq
JOIN times t ON seq.seq >= t.time_from
AND seq.seq < t.time_to
最后,使用COUNT(DISTINCT seq) hours
总结一下,您可以获得原始表格中一个或多个时间间隔内显示的小时数。 (http://sqlfiddle.com/#!9/57cf7f/10/0)
SELECT COUNT(DISTINCT seq) hours
FROM (
SELECT seq.seq, t.*
FROM (
SELECT 1 seq UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13
UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17
UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24
) seq
JOIN times t ON seq.seq >= t.time_from
AND seq.seq < t.time_to
) a
这是MariaDB中的样子。
SELECT COUNT(DISTINCT seq) hours
FROM (
SELECT seq.seq
FROM seq_1_to_24 seq
JOIN times t ON seq.seq >= t.time_from
AND seq.seq < t.time_to
) a
答案 1 :(得分:0)
以下解决方案假定Sub WhatTheHeck()
If Selection.Font.Bold = True Then MsgBox "All is Bold"
If Selection.Font.Bold = False Then MsgBox "None is Bold"
If Selection.Font.Bold = wdUndefined Then MsgBox "Some is Bold"
End Sub
和time_from
都按升序排序,并且重叠仅在相邻行之间发生:
time_to