2016-09-26 44 views
0

有看起來像這樣(有更多的列,但不相關的查詢)的表:檢查SQL中的表中是否連續出現兩個不同的值?

DocumentId | DocumentStateId | TransitionMoment 
111222  -2    2016-04-21 
111222  -1    2016-04-22 
111222  -7    2016-04-23 
111222  -5    2016-04-24 
111222  -6    2016-04-25 
111222  -1    2016-04-26 
333141  -2    2016-05-01 
333141  -7    2016-05-09 
333141  -6    2016-05-10 
333141  -3    2016-05-15 
777525  -1    2016-02-10 
777525  -6    2016-02-10 
777525  -7    2016-02-10 
777525  -5    2016-02-10 
777525  -2    2016-02-10 

做什麼選擇我要檢查文檔是否已經從國家去「-7」國家「-6」連續(不經過其他州之間的轉換)?在示例文檔編號33141.

在此先感謝!

+0

一個DocumentId可以擁有多個-7值,或-6的值? – jarlh

+0

是的,它可以有多個-7或-6的值 –

回答

0

在SQL Server 2012+中,您只需使用lag()。在SQL Server 2005中,你可以使用apply

select t.* 
from t cross apply 
    (select top 1 t2.* 
     from t t2 
     where t2.documentid = t.documentid and 
      t2.transitionmoment > t.transitionmoment 
     order by t2.transitionmoment desc 
    ) tnext 
where t.DocumentStateId = -7 and 
     tnext.DocumentStateId = -6; 
+0

謝謝!只需稍作更改,應用程序就能正常工作。 –

0

使用鉛():

WITH CTE AS 
(
SELECT 
DocumentId, DocumentStateId, TransitionMoment, 
LEAD(DocumentStateId) OVER (ORDER BY TransitionMoment) NextSIDVal, 
LEAD(DocumentId) OVER (ORDER BY DocumentId) NextDIDVal 
FROM Table 
) 

SELECT DocumentId, DocumentStateId, TransitionMoment FROM CTE 
WHERE DocumentStateId = -7 AND NextSIDVal = -6 
AND DocumentId = NextDIDVal 

使用ROW_NUMBER():

WITH CTE AS 
(
SELECT 
DocumentId, DocumentStateId, TransitionMoment, ROW_NUMBER() OVER (ORDER BY TransitionMoment) RowVal 
FROM Table 
) 

SELECT x.DocumentId, x.DocumentStateId, x.TransitionMoment 
FROM CTE x 
JOIN CTE y 
ON x.RowVal + 1 = y.RowVal 
WHERE x.DocumentStateId = -7 AND y.DocumentStateId = -6 
AND x.DocumentId = y.DocumentId 
相關問題