使用SQL Server 2016按时间顺序对活动进行分组

时间:2017-08-31 17:07:00

标签: sql tsql sql-server-2016

我正在分析它的一段时间。我知道这段时间从00:00开始,到00:15之前结束。我还有一个包含这些信息的表格:

create table #Activities (Description varchar(25),[Start] Time2(7),[End] time2(7))
insert into #Activities ([Description],[Start],[End]) select 'Break 1','00:04','00:07:59.9999999'
insert into #Activities ([Description],[Start],[End]) select 'Break 1','00:12','00:14:59.9999999'

我正在寻找一个看起来像这样的输出 enter image description here

不使用光标实现此目的的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

common table expression中使用lag()(子查询也可以正常工作)。:

;with cte as (
  select Description, Start,[End]
    , lag([end]) over (order by start)as PrevEnd
  from #activities
)
select Description, Start,[End]
from #activities
union all
select 
    'Not a break '+convert(varchar(10),row_number() over(order by start))
  , isnull(dateadd(nanosecond,100,PrevEnd),'00:00')
  , dateadd(nanosecond,-100,Start)
from cte
where isnull(dateadd(nanosecond,100,PrevEnd),'00:00')<>Start
order by start,[End]

rextester演示:http://rextester.com/DQI53300

返回:

+---------------+----------+------------------+
|  Description  |  Start   |       End        |
+---------------+----------+------------------+
| Not a break 1 | 00:00:00 | 00:03:59.9999999 |
| Break 1       | 00:04:00 | 00:07:59.9999999 |
| Not a break 2 | 00:08:00 | 00:11:59.9999999 |
| Break 1       | 00:12:00 | 00:14:59.9999999 |
+---------------+----------+------------------+