T-SQL从两个日期生成间隔

时间:2018-04-12 08:12:23

标签: sql tsql

我想生成这样的间隔:

 - ID | START_INTERVAL
 - 1 | 12:00
 - 2 | 12:30
 - 3 | 13:00
 - 4 | 13:30
 - 5 | 16:00
 - 6 | 16:30
 - 7 | 17:00
 - 8 | 17:30

由此:

- ID | START | STOP | INTERVAL
 - 1 | 2018-05-03 12:00:00 | 2018-05-03 14:00:00 | 30
 - 2 | 2018-05-03 16:00:00 | 2018-05-03 18:00:00 | 30

可以从t-sql生成这个,或者我需要使用PHP吗?

1 个答案:

答案 0 :(得分:2)

所以,你想要某种递归 cte

with cte as (
    select id, start, stop, interval from table t
    union all
    select id, dateadd(MINUTE, interval, start) start, stop, interval
    from cte c
    where start < stop
)
select id, start as start_interval from cte c
order by 1