TSQL自联接:排除具有设置标准的连续ID记录

时间:2012-09-28 19:00:02

标签: sql sql-server-2008 tsql

我有一张表格如下:

ID, DATE, STATUS
1, 01JAN2012, STOP
1, 04JAN2012, RESTART
2, 01JAN2012, STOP-1
3, 10JAN2012, STOP
4, 15JAN2012, RESTART
5, 01JAN2012, STOP-1
5, 04JAN2012, STOP-2
5, 10JAN2012, STOP
5, 15JAN2012, RESTART

预期产出:

ID, DATE, STATUS
2, 01JAN2012, STOP-1
3, 10JAN2012, STOP
4, 15JAN2012, RESTART
5, 01JAN2012, STOP-1
5, 04JAN2012, STOP-2

我希望SELECT语句排除具有相同ID的所有记录(STATUS ='RESTART')和一个连续的先前记录(如果可用)。

1 个答案:

答案 0 :(得分:3)

我不确定如果有两个连续的RESTART会发生什么,但除非出现这样的并发症,我想你可能会想要这样的事情:

;WITH myTable AS(
SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [DATE]) AS rn
FROM OriginalTable
)
SELECT this.ID, this.DATE, this.STATUS
FROM myTable this
LEFT OUTER JOIN myTable prev ON prev.ID = this.ID and prev.rn = this.rn-1
LEFT OUTER JOIN myTable nxt ON nxt.ID = this.ID and nxt.rn = this.rn+1
WHERE NOT ((this.STATUS= 'RESTART' AND prev.STATUS IS NOT NULL)
           OR (COALESCE(nxt.STATUS,'') = 'RESTART'))

我假设你的DATE列是date或datetime类型,但是如果它是一个字符串,你应该将它转换为ROW_NUMBER调用的ORDER BY部分中的日期。