我正在努力根据下表编写一个查询,该查询应该获取位置的错误记录(其中BadRec = 1)以及该位置上的前3条记录(Max),包括错误记录;
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
这是预期的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-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机器上;
答案 0 :(得分: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