开发者

SQL Query to find previous records

I am struggling to write a query based on the table below that should get Bad records for a Location (where BadRec =1) and also previous 3 records(Max) on that Location including bad records;

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

Here is the expected out Put;

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-开发者_StackOverflow中文版26 00:00:00.000  STN-2     1    <- Bad record on STN-2
2010-08-25 00:00:00.000  STN-2     0    

Is this possible to write this using a single query?? Using CTE?? Over (partition…)?? Any help is well appreciated. Note: I am on a SQL 2005 machine;


Does this do what you want?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜