更新CTE以插入创建新记录链接日期时间

时间:2019-07-10 18:11:06

标签: sql-server tsql

我有以下CTE:

with cte as 
(
    select 
        fromtime,
        (case 
            when datediff(day, fromtime, totime) = 0
               then totime
            else dateadd(day, 1, convert(date, fromtime))
         end) as dayendtime,
        totime
    from 
        t
    union all
    select 
        dayendtime as fromtime,
        (case 
            when datediff(day, dayendtime, totime) = 0
               then totime
               else dateadd(day, 1, dayendtime)
         end) as dayendtime,
        totime
    from  
        cte
    where 
        dayendtime < totime
)

输出如下数据:

enter image description here

效果很好,但是现在我想链接创建一个新行,例如,如果DayEndTime是午夜,则将FromTime链接到下一条记录的DayEndTime,例如:

enter image description here

谁能给我有关如何实现的指导?谢谢!

1 个答案:

答案 0 :(得分:1)

with cte 
as (
      select fromtime,
             (case when datediff(day, fromtime, totime) = 0
                   then totime
                   else dateadd(day, 1, convert(date, fromtime))
              end) as dayendtime,
             totime
      from t
      union all
      select dayendtime as fromtime,
             (case when datediff(day, dayendtime, totime) = 0
                   then totime
                   else dateadd(day, 1, dayendtime)
              end) as dayendtime,
             totime
       from cte
       where dayendtime < totime
),
cte_new 
as (
  SELECT dayendtime AS fromtime,totime AS dayendtime,totime 
  FROM cte
  WHERE dayendtime=cast(dayendtime AS date)
)
SELECT *
FROM cte
UNION ALL
SELECT *
FROM cte_new
ORDER BY fromtime;