SQL Server 2008 Combine \ Merge行,其中一行的结束时间是另一行的开始时间

时间:2015-09-28 21:52:05

标签: sql sql-server-2008

尽管这个助手非常相似,但我无法解决这个问题。

Combine rows when the end time of one is the start time of another (Oracle)

示例数据

String myStr = "[3:0]";
if (myStr.trim().matches("\\[(\\d+)\\]")) {
    // Do something.
    // If it enter the here, here I want to store 3 and 0 in different variables or an array
} 

我想要的输出。

groupId startTime               endTime
-------------------------------------------------------
1022    2015-09-14 06:30:00.000 2015-09-14 13:45:00.000
1022    2015-09-14 11:20:00.000 2015-09-14 11:50:00.000
1477    2015-09-14 09:46:00.000 2015-09-14 16:13:00.000
1477    2015-09-14 13:40:00.000 2015-09-14 14:10:00.000
2037    2015-09-14 09:43:00.000 2015-09-14 12:00:00.000
2037    2015-09-14 12:00:00.000 2015-09-14 19:02:00.000
2037    2015-09-14 14:00:00.000 2015-09-14 14:30:00.000

示例sql。

groupId startTime               endTime
-------------------------------------------------------
1022    2015-09-14 06:30:00.000 2015-09-14 13:45:00.000
1022    2015-09-14 11:20:00.000 2015-09-14 11:50:00.000
1477    2015-09-14 09:46:00.000 2015-09-14 16:13:00.000
1477    2015-09-14 13:40:00.000 2015-09-14 14:10:00.000
2037    2015-09-14 09:43:00.000 2015-09-14 19:02:00.000
2037    2015-09-14 14:00:00.000 2015-09-14 14:30:00.000

谢谢。

1 个答案:

答案 0 :(得分:0)

也许是一种更好的方式但是当有疑问时CTE ......

WITH CTES as 
(select * from #data)

select c.groupid,c.starttime,ISNULL(d.endtime,c.endtime)
FROM CTES c
left join CTES d
on c.starttime = d.endtime
and c.groupid = d.groupid
where c.starttime != ISNULL(d.endtime,c.endtime)