Sql 递归CTE以查找当前和以前的工作状态以及工作状态的输入时间

Sql 递归CTE以查找当前和以前的工作状态以及工作状态的输入时间,sql,sql-server,tsql,sql-server-2016,Sql,Sql Server,Tsql,Sql Server 2016,我有下面的 模式如下所示 declare @t table(CustomerId varchar(10),WorkState varchar(10),statechangedate datetimeoffset, stateorder int) insert into @t select '1','WorkStateA','2018-10-30 13:38:53.5133333 +00:00',1 union all select '2','WorkStateA','2018

我有下面的

模式如下所示

declare @t table(CustomerId varchar(10),WorkState varchar(10),statechangedate datetimeoffset, stateorder int)
insert into @t 
    select '1','WorkStateA','2018-10-30 13:38:53.5133333 +00:00',1 union all
    select '2','WorkStateA','2018-05-18 17:04:56.9900000 +00:00',1 union all
    select '2','WorkStateA','2018-05-18 16:22:20.3266667 +00:00',2 union all
    select '2','WorkStateB','2018-05-09 12:46:33.8300000 +00:00',3 union all
    select '3','WorkStateF','2018-06-21 12:40:03.2933333 +00:00',1 union all
    select '3','WorkStateE','2018-06-21 12:38:43.9000000 +00:00',2 union all
    select '3','WorkStateD','2018-06-21 12:38:24.7533333 +00:00',3 union all
    select '3','WorkStateC','2018-06-21 12:38:11.0233333 +00:00',4 union all
    select '3','WorkStateB','2018-06-21 12:38:04.1933333 +00:00',5 union all
    select '3','WorkStateA','2018-06-21 12:36:51.4633333 +00:00',6 
select * from @t
我在找什么

意味着我需要根据客户情况捕获当前和以前的工作状态以及工作状态的进入时间

我已尝试使用以下递归CTE

;with cte as(
select 
    t.CustomerId, 
    PresentWorkState = t.WorkState,
    PresentStatechangedate = t.statechangedate, 
    t.stateorder, 
    PreviousWorkState = null ,
    PreviousStatechangedate=  null 
from @t t where t.stateorder=1
union all
select 
    t1.CustomerId, 
    t1.WorkState,
    t1.statechangedate, 
    c.stateorder,
    c.PreviousWorkState,
    c.PreviousStatechangedate
from  @t t1
join cte c on t1.stateorder !=c.stateorder)

select *
from cte
但是不能。

就像Andrew说的那样,
LAG()
应该为您的目的而工作,而不是使用递归cte。选中此项:

SELECT *
        ,LAG(WorkState) OVER(PARTITION BY CustomerId ORDER BY statechangedate)
        ,LAG(statechangedate) OVER(PARTITION BY CustomerId ORDER BY statechangedate)
FROM @T
ORDER BY CustomerId,statechangedate
(代表问题作者张贴)

领导功能解决了这个问题。以下是输出:

select 
    CustomerId,
    PresentWorkState = WorkState,
    PresentStatechangedate = statechangedate,
    PreviousWorkState = LEAD(WorkState) OVER (partition by CustomerId ORDER BY stateorder) ,
    PreviousStatechangedate = LAG(statechangedate) OVER (partition by CustomerId ORDER BY stateorder)
from @t

您使用的是哪种数据库管理系统?sql server?是的,sql server 2016当你说prevoius时,我猜你指的是之前的一个工作状态,而不是之前的所有状态-如果是这样,它不是递归。看起来你不需要递归CTE,但是(或)窗口函数。是的,你是对的。领导职能部门做到了。谢谢@Andrey,虽然我已经接受了Zeki Gumus的回答,但非常感谢你的指点。不,这是Lead函数。我刚试过。我的意思是滞后也是正确的,这是另一种方式around@priyanka.sarkar你确定是LEAD()吗。对于预期结果,似乎需要使用LAG()。