2016-09-26 51 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 
相关问题