输入表
Start time End Time
8/12/14 17:00 8/14/14 12:00
我需要将时间拆分并显示输出如下
11:00 to 23:00 23:00 to 11:00
19 24
计算工作
Date 11:00 to 23:00 23:00 to 11:00
8/12/14 6 1
8/13/14 12 12
8/14/14 1 11
Total 19 24
答案 0 :(得分:1)
您可以使用递归公用表表达式生成开始日期和结束日期之间的小时序列,然后使用case语句来评估它所属的范围,然后求和汇总:
DECLARE @T TABLE (StartTime DATETIME, EndTime DATETIME)
INSERT @T VALUES ('8/12/14 17:00', '8/14/14 12:00')
;WITH cte AS
(
SELECT StartTime AS dt, EndTime
FROM @T
UNION ALL
SELECT DATEADD(MINUTE, 60, dt) AS dt, EndTime
FROM cte
WHERE dt < DATEADD(HOUR, -1, EndTime)
)
SELECT
SUM(
CASE
WHEN CAST(dt AS TIME) >= '11:00' AND CAST(dt AS TIME) < '23:00' THEN 1
ELSE 0
END) AS '11:00 to 23:00',
SUM(
CASE
WHEN CAST(dt AS TIME) >= '11:00' AND CAST(dt AS TIME) < '23:00' THEN 0
ELSE 1
END) AS '23:00 to 11:00'
FROM cte
我确信它可以改进但它应该能给你想要的结果。
示例输出:
11:00 to 23:00 23:00 to 11:00
-------------- --------------
19 24
此SQL Fiddle以30分钟为间隔显示处理时间,输出为:
11:00 to 23:00 23:00 to 11:00
-------------- --------------
23.5 25.5