【问题标题】:Check if two different values appear successively in a table in SQL?检查SQL中的表中是否连续出现两个不同的值?
【发布时间】:2016-09-26 12:55:33
【问题描述】:

有一个表是这样的(列比较多,但与查询无关):

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.

提前致谢!

【问题讨论】:

  • 一个 DocumentId 可以有多个 -7 值还是 -6 值?
  • 是的,它可以有多个 -7 或 -6 值

标签: sql sql-server sql-server-2005


【解决方案1】:

在 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;

【讨论】:

    【解决方案2】:

    使用 LEAD():

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2015-01-10
      • 2021-11-29
      • 2021-07-20
      相关资源
      最近更新 更多