我需要有关sql表的帮助。
该表包含以下列:
EventID,PersonID,EventType,EventTime(datetime)以及其他一些不太重要的列。
让我们说两个主要的事件类型是打开一扇门并关上一扇门。
我需要同一个人打开一扇门和关门之间的持续时间(以秒为单位),或者他打开一扇门并打开另一扇门。(这当然只允许打开门的顺序)
为了清楚,如果第1人开门,而第2人关门,则不应该从查询中返回任何行。
我希望它有效但不是必须的。
我正在使用2008 SQL微软服务器(SQLEXPRESS)
以下是表格的示例:
EventID | PersonID | EventType | EventDate | PreviousDoor | CurrentDoor
1 | 1 | 1 | 12/10/2010 12:00:01.024 | 0 | 23
2 | 1 | 2 | 12/10/2010 12:05:40.758 | 23 | 0
3 | 2 | 1 | 12/10/2010 12:12:05.347 | 0 | 12
4 | 1 | 1 | 12/10/2010 12:50:12.142 | 0 | 23
5 | 2 | 2 | 12/10/2010 13:00:06.468 | 12 | 23
6 | 3 | 1 | 13/10/2010 13:00:06.468 | 0 | 23
EventType:1(已打开的门),2(已关闭的门)
结果应该是:
EventID | PersonID | EventType | EventDate | SecondsDifference
1 | 1 | 1 | 12/10/2010 12:00:01.024 | 339
3 | 2 | 1 | 12/10/2010 12:12:05.347 | 2881
我真的可以帮助你们。
提前致谢。
答案 0 :(得分:1)
我认为应该这样做:
SELECT p1.EventID,
p1.PersonID,
p1.EventType,
p1.EventDate,
DATEDIFF(SECOND, p1.EventDate, p2.EventDate) AS SecondsDifference
FROM [Event] p1
LEFT JOIN [Event] p2 --Left join to self returning only closed door events
ON p2.PersonID = p1.PersonID
AND p2.EventType = 2 -- Closed Door
AND p1.EventID < p2.EventID --We don't want to bring back events that happened before the next event
WHERE p2.EventID IS NOT NULL --We don't want to show any people that have not closed a door
答案 1 :(得分:1)
尝试这样的事情:
select t1.EventID, t1.PersonID, t1.EventType, t1.EventDate, datediff(second, t1.EventDate, t2.EventDate) as 'SecondsDifference'
from [Event] t1
inner join [Event] t2 on t2.PersonID = t1.PersonID and t2.EventType = 2 and t2.PreviousDoor = t2.CurrentDoor and t2.EventID < t1.EventID
where t1.EventType = 1
答案 2 :(得分:1)
使用ROW_NUMBER
和PARTITION
会有帮助吗?
我不确定以下是否是合法的SQL语句,因此请将其视为半伪代码。
SELECT *,
ROW_NUMBER() OVER(PARTITION BY PersonID ORDER BY EventTime) AS RowNumber,
datediff(seconds, t2.EventTime, t1.EventTime) AS SecondsDiff
FROM Events t1
INNER JOIN
SELECT *,
ROW_NUMBER() OVER(PARTITION BY PersonID ORDER BY EventTime) AS RowNumber
From Events t2
ON t1.RowNumber + 1 = t2.RowNumber
AND t1.PersonID = t2.PersonID AND t1.EventType = 1
AND (t2.EventType = 1 OR t2.EventType = 2)