2011-08-04 198 views
1

我很努力地寫一個基於下面的表的查詢應該得到一個位置(其中BadRec = 1)的Bad記錄以及該位置上的前3個記錄(Max),包括壞記錄;SQL查詢查找以前的記錄

TranDate    Location BadRec 
======================= ======== ====== 
2010-08-25 00:00:00.000 STN-2  0 
2010-08-26 00:00:00.000 STN-2  1 
2010-08-27 00:00:00.000 STN-1  1 
2010-08-28 00:00:00.000 STN-1  0 
2010-08-28 00:00:00.000 STN-2  1 
2010-08-29 00:00:00.000 STN-1  0 
2010-08-30 00:00:00.000 STN-1  1 
2010-08-31 00:00:00.000 STN-1  0 
2010-09-01 00:00:00.000 STN-1  0 

這裏是預期的推出;

TranDate    Location BadRec comments 
======================= ======== ====== ======== 
2010-08-30 00:00:00.000 STN-1  1 <- Bad record on STN-1 
2010-08-29 00:00:00.000 STN-1  0 <- First Previous record 
2010-08-28 00:00:00.000 STN-1  0 <- Second Previous record 
2010-08-27 00:00:00.000 STN-1  1 <- Third Previous record (Previous include bad rec) 
2010-08-28 00:00:00.000 STN-2  1 <- Bad record on STN-2 
2010-08-26 00:00:00.000 STN-2  1  
2010-08-25 00:00:00.000 STN-2  0  
2010-08-27 00:00:00.000 STN-1  1 <- Bad record on STN-1,No previous record for this 
2010-08-26 00:00:00.000 STN-2  1 <- Bad record on STN-2 
2010-08-25 00:00:00.000 STN-2  0  

這是可能寫這個使用單個查詢?使用CTE?結束(分區...)??任何幫助,非常感謝。 注意:我在SQL 2005機器上;

+1

爲什麼'2010-08-27 00:00:00.000 STN-1 1'在預期輸出中重複兩次? – Chandu

+0

我認爲'2010-08-27 00:00:00.000 STN-1 1'首先出現在2010-08-30的前一行,第二行作爲BadRec行出現。 – bobs

+0

謝謝鮑勃!那正是我正在尋找的!感謝您的幫助 – user173552

回答

1

這是做你想做的嗎?

SELECT TranDate, Location, BadRec 
FROM 
    (
    SELECT pr.TranDate, pr.Location, pr.BadRec, 
     ROW_NUMBER() OVER (PARTITION BY r.TranDate ORDER BY pr.TranDate DESC) AS SEQUENCE 
    FROM Records r 
    JOIN Records pr ON r.Location = pr.Location 
        AND r.TranDate >= pr.TranDate 
    WHERE r.BadRec = 1 
    ) x 
WHERE SEQUENCE <= 4 
+0

+1,添加一個訂單也許有完全相同的結果:http://data.stackexchange.com/stackoverflow/qe/1683/sql-query-to-find-previous-records –