我希望能够计算SQL Server 2008中某些事件之间的总时间。
我有一张表格如下:
UserId Event EventTimestamp
+-------+----------+---------------+
1 CheckedIn 14-05-15 10:01
2 CheckedIn 14-05-15 10:15
3 CheckedIn 14-05-15 10:17
1 CheckedOut 14-05-15 10:25
1 Logout 14-05-15 10:26
如果您查看表格,用户可以办理登机手续,然后可以退房,然后离线。
我想计算一个人登记到他们结账的点之间的时间,每个星期的持续时间(登记入住和结账时间)小于10分钟。
到目前为止,我已成功按周分组,但我似乎无法计算这些事件之间的持续时间(将按此顺序发生)...
select
'Week ' + cast(datepart(wk, EventUpdateStamp) as varchar(2)) Week,
UserId,
Event
from MyTable
group by datepart(wk, EventUpdateStamp), UserId, Event
我希望得到如下结果:
UserId TotalSessionCheckInTimeMinutes WeekNumber
+-------+------------------------------+---------------+
1 24 43
以第一行为例:
我只想在办理登机手续时办理登机手续。不想在退房和退出之间进行衡量(换句话说,衡量他登记的时间)。
答案 0 :(得分:4)
试试这个:
SELECT t1.UserId,
DATEDIFF(minute,
t1.EventTimestamp,
(SELECT MIN(t3.EventTimestamp)
FROM MyTable t3
WHERE t3.UserId = t1.UserId
AND t3.EventTimestamp> t1.EventTimestamp)
),
CAST(DATEPART(wk, EventTimestamp) as varchar(2)) Week
FROM MyTable t1
WHERE EXISTS(
SELECT 'NEXT'
FROM MyTable t2
WHERE t2.UserId = t1.UserId
AND t2.EventTimestamp> t1.EventTimestamp
AND t2.Event != 'Logout')
<强> SqlFiddle 强>
转到here
答案 1 :(得分:1)
你可以试试这个:
SELECT DISTINCT M.UserId, DATEPART(HOUR,A.TotalSessionCheckInTimeMinutes)*60 + DATEPART(MINUTE,A.TotalSessionCheckInTimeMinutes) AS TotalSessionCheckInTimeMinutes, DATEPART(WEEKDAY, M.EventTimestamp) FROM Mytable M
CROSS APPLY (
SELECT CAST((M1.EventTimestamp - M2.EventTimestamp) AS TIME) AS TotalSessionCheckInTimeMinutes
FROM Mytable M1
CROSS JOIN Mytable M2
WHERE M1.Event = 'CheckOut' AND M2.Event = 'CheckIn' AND M1.UserId = M.UserId) AS A
UNION ALL
SELECT DISTINCT M.UserId, A.TotalSessionCheckInTimeMinutes, DATEPART(WEEKDAY, M.EventTimestamp) FROM Mytable M
CROSS APPLY (
SELECT CAST((M1.EventTimestamp - M2.EventTimestamp) AS TIME) AS TotalSessionCheckInTimeMinutes
FROM Mytable M1
CROSS JOIN Mytable M2
WHERE M1.Event = 'LogOut' AND M2.Event = 'CheckIn' AND M1.UserId = M.UserId) AS A