我有以下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
)
输出如下数据:
效果很好,但是现在我想链接创建一个新行,例如,如果DayEndTime
是午夜,则将FromTime
链接到下一条记录的DayEndTime
,例如:>
谁能给我有关如何实现的指导?谢谢!
答案 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;