问题
你好,大家好。
我需要一些帮助来计算办理登机手续和退房员工白天和夜班工作之间的时间间隔。下面是表结构和查询的期望结果。有人可以帮忙吗?
签入和签出表格
EventTime User Status Date
12/30/2017 6:38 User 1 Exit 12/30/2017
12/29/2017 18:18 User 1 Entry 12/29/2017
12/29/2017 17:14 User 4 Exit 12/29/2017
12/29/2017 9:14 User 4 Entry 12/29/2017
12/29/2017 18:23 User 2 Exit 12/29/2017
12/29/2017 6:33 User 2 Entry 12/29/2017
12/30/2017 6:38 User 3 Exit 12/30/2017
12/29/2017 18:18 User 3 Entry 12/29/2017
期望的结果:
User Entry Exit Time duration Date
User 1 12/29/2017 18:18 12/30/2017 6:38 12:19:56 12/29/2017
User 2 12/29/2017 6:33 12/29/2017 18:23 11:49:52 12/29/2017
User 3 12/29/2017 18:18 12/30/2017 6:38 12:19:56 12/29/2017
User 4 12/29/2017 9:14 12/29/2017 17:14 8:00:00 12/29/2017
答案 0 :(得分:0)
条件聚合是一种方法
select t.[User], max(case when t.[status] = 'Entry' then t.EventTime end) [Entry],
max(case when t.[status] = 'Exit' then t.EventTime end) [Exist],
cast(cast(max(case when t.[status] = 'Exit' then t.EventTime end) as datetime) -
cast(max(case when t.[status] = 'Entry' then t.EventTime end) as datetime) as time) [Time duration],
max(case when t.[status] = 'Entry' then t.[date] end) [Date]
from table t
group by t.[User]
注意:在上面用作varchar类型的日期时间,因为显然需要一些转换到datateime。所以,避免它。
结果:
User Entry Exist Time duration Date
User 1 12/29/2017 18:18 12/30/2017 6:38 12:20:00.0000000 12/29/2017
User 2 12/29/2017 6:33 12/29/2017 18:23 11:50:00.0000000 12/29/2017
User 3 12/29/2017 18:18 12/30/2017 6:38 12:20:00.0000000 12/29/2017
User 4 12/29/2017 9:14 12/29/2017 17:14 08:00:00.0000000 12/29/2017
答案 1 :(得分:0)
以下是您的解决方案......
SELECT EntryDtls.UserName,
EntryDtls.EventTime AS Entry,
ExitDtls.EventTime AS ExitDt,
CAST(DATEDIFF(second, EntryDtls.EventTime, ExitDtls.EventTime) /
60 / 60 % 24 AS NVARCHAR(50)) +':'+
CAST(DATEDIFF(second, EntryDtls.EventTime, ExitDtls.EventTime) /
60 % 60 AS NVARCHAR(50)) +':'+
CAST(DATEDIFF(second, EntryDtls.EventTime, ExitDtls.EventTime) %
60 AS NVARCHAR(50)) AS
Time_duration,
EntryDtls.Date
FROM (SELECT *
FROM Trans_Tab
WHERE Status = 'Entry') AS EntryDtls
JOIN (SELECT *
FROM Trans_Tab
WHERE Status = 'Exit') AS ExitDtls
ON (EntryDtls.UserName = ExitDtls.UserName)