SQL-服務器2012+,使用LAG()
功能:
; WITH cte AS
(SELECT Revision, Value,
PreviousValue = LAG(Value) OVER (ORDER BY Revision)
FROM tableX
)
SELECT Revision, Value
FROM cte
WHERE Previousvalue <> Value
OR PreviousValue IS NULL ;
SQL-服務器2005+,利用窗口函數:
; WITH cte AS
(SELECT Revision, Value,
Rn = ROW_NUMBER() OVER (ORDER BY Revision),
Ln = ROW_NUMBER() OVER (PARTITION BY Value ORDER BY Revision)
FROM tableX
)
SELECT Revision = MIN(Revision),
Value
FROM cte
GROUP BY Value, (Rn-Ln) ;
在SQL-Fiddle.com
注意,這兩個測試查詢不依賴於Revision
數字順序(甚至是數字!)。如果你的數字沒有差距,GoatCO的回答也相當不錯。
SQL-Server的版本? –
查找滯後和領導 –
Microsoft SQL Server 2008 R2(SP1) – Sebastian