当前表:
Name State Start Time
A Start 17/01 2pm
A update 17/01 4pm
B Start 18/01 3pm
B Start 18/01 5pm
C Start 18/01 6pm
B Start 19/01 2pm
我正在寻找的输出:
Name StartTime End Time
A 17/01 2pm 17/01 4pm
B 17/01 4pm 18/01 5pm
C 18/01 5pm 18/01 6pm
B 18/01 6pm 19/01 2pm
有人可以建议吗?
答案 0 :(得分:0)
根据您的评论,应使用窗口功能LAG或LEAD。看下面的示例代码:
LAG:访问同一结果集中上一行的数据。
LEAD:访问同一结果集中下一行的数据。
with
cte
as
(
select
[Name] ,
[State] ,
lag(StartTime) over(order by [Name], [State], StartTime) as StartTime ,
StartTime as EndTime
from
dbo.Test
)
select
[Name] ,
[State] ,
min(StartTime) as StartTime ,
max(EndTime) as EndTime
from
cte
group by
[Name] ,
[State]