2011-12-16 28 views
0

我需要一個sql表的幫助。SQL查詢的問題

表包含以下幾列:

事件ID,是PersonID,事件類型,EVENTTIME(日期時間),以及其他一些不太顯著列。

可以說,兩種主要事件類型是打開一扇門,關上一扇門。

我需要同樣的人打開一扇門,關閉它或他打開一扇門,打開一個又一個的持續時間(以秒爲單位)。(這當然是允許簡單地打開門的序列)

只是爲了如果人員1打開了一扇門,並且人員2關閉了一扇門,則不應該從查詢中返回行。

我希望它是有效的,但這不是必須的。

我使用的是SQL 2008 Microsoft服務器(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 

事件類型: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 

我真的可以用你的球員的幫助。

在此先感謝。

回答

1

將使用ROW_NUMBERPARTITION幫助? 我不確定以下是否是合法的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) 
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 
+2

我建議打開LEFT JOIN到INNER JOIN(使`p2.EventID IS NOT NULL`冗餘) - OP只希望配對的打開/關閉事件 - 並添加一個'WHERE p1.EventType = 1`條件。 – 2011-12-16 17:31:39

+1

@KevRitchie爲什麼`LEFT JOIN`?和..你需要使用`CurrentDoor`和`PreviousDoor`獲得更好的結果:) – 2011-12-16 17:32:24

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