首页 > 解决方案 > SQL:使用移位获取两个日期之间的所有日期

问题描述

我有一个包含“startbooking”和“endbooking”列的表格我还有其他内容包含转变:

id |start  |end
M  | 06:00 |14:00
T  | 14:00 |20:00
N  | 20:00 |06:00

所以,我需要通过班次获取开始预订和结束预订之间的所有日期

例子:

startbooking: 01/05/2015 12:00  endbooking: 02/05/2015 16:00

结果:

01/05/2015 |M
01/05/2015 |T
01/05/2015 |N
02/05/2015 |M
02/05/2015 |T

标签: sqlsql-server

解决方案


也许您需要使用join进行递归: ctecross

with t as (
     select startdt, enddt
     from table
     union all
     select dateadd(day, 1, startdt), enddt
     from t
     where startdt < enddt
)

select t.startdt, sft.id
from t cross join (select distinct id from shifttable) sft
option (maxrecursion 0);

这是一个演示


推荐阅读