TSQL - 从连续的计划部分创建合并计划

时间:2017-01-23 15:12:22

标签: sql sql-server tsql sql-server-2012

在开始和结束时间匹配时,我正在尝试将计划部分列表合并到一个更简洁的列表中,这是绝对最糟糕的时间。下面的代码用于单个计划,代码是对用户当时正在发生的事情的引用。

任何想法都将不胜感激!

declare @t as table (code int, dtDate DateTime, dtStart DateTime, dtEnd DateTime)

insert into @t values
(46,'2017-01-23','2017-01-23 06:00','2017-01-23 14:45'),
(127,'2017-01-23','2017-01-23 07:30','2017-01-23 08:00'),
(127,'2017-01-23','2017-01-23 08:00','2017-01-23 08:15'),
(127,'2017-01-23','2017-01-23 08:15','2017-01-23 10:00'),
(76,'2017-01-23','2017-01-23 10:00','2017-01-23 10:45'),
(127,'2017-01-23','2017-01-23 10:45','2017-01-23 13:00'),
(127,'2017-01-23','2017-01-23 13:00','2017-01-23 13:15'),
(127,'2017-01-23','2017-01-23 13:15','2017-01-23 14:30')

select * from @t


-- Current Output
code        dtDate                  dtStart                 dtEnd
----------- ----------------------- ----------------------- -----------------------
46          2017-01-23 00:00:00.000 2017-01-23 06:00:00.000 2017-01-23 14:45:00.000
127         2017-01-23 00:00:00.000 2017-01-23 07:30:00.000 2017-01-23 08:00:00.000
127         2017-01-23 00:00:00.000 2017-01-23 08:00:00.000 2017-01-23 08:15:00.000
127         2017-01-23 00:00:00.000 2017-01-23 08:15:00.000 2017-01-23 10:00:00.000
76          2017-01-23 00:00:00.000 2017-01-23 10:00:00.000 2017-01-23 10:45:00.000
127         2017-01-23 00:00:00.000 2017-01-23 10:45:00.000 2017-01-23 13:00:00.000
127         2017-01-23 00:00:00.000 2017-01-23 13:00:00.000 2017-01-23 13:15:00.000
127         2017-01-23 00:00:00.000 2017-01-23 13:15:00.000 2017-01-23 14:30:00.000

-- Expected Output
code        dtDate                  dtStart                 dtEnd
----------- ----------------------- ----------------------- -----------------------
46          2017-01-23 00:00:00.000 2017-01-23 06:00:00.000 2017-01-23 14:45:00.000
127         2017-01-23 00:00:00.000 2017-01-23 07:30:00.000 2017-01-23 10:00:00.000
76          2017-01-23 00:00:00.000 2017-01-23 10:00:00.000 2017-01-23 10:45:00.000
127         2017-01-23 00:00:00.000 2017-01-23 10:45:00.000 2017-01-23 14:30:00.000

1 个答案:

答案 0 :(得分:0)

看起来像一个经典的Gaps&岛

Select Code
      ,dtDate
      ,dtStart = min(dtStart)
      ,dtEnd   = max(dtEnd)
 From  (
        Select * 
              ,Grp = Row_Number() over (Partition By Code,dtDate Order By dtStart) - Row_Number() over (Order by dtEnd)
         From @t
       ) A
 Group By Code,dtDate,Grp
 Order By min(dtStart)

返回

enter image description here