SQL 添加额外的行直到日期 (YYYYMMDD) 列匹配
SQL Adding extra rows until dates (YYYYMMDD) columns match
表 1:
ID|StartDateID|EndDateID
468|20200101|20200104
534|20200103|20200104
123|20200106|20200108
要求输出:
ID|StartDateID|EndDateID
468|20200101|20200104
468|20200102|20200104
468|20200103|20200104
468|20200104|20200104
534|20200103|20200104
534|20200104|20200104
123|20200106|20200108
123|20200107|20200108
123|20200108|20200108
如果解释不当,我们深表歉意。表 1 列出了任务完成的开始和结束日期。每个 ID 都是一个唯一的条目。
我需要为每个 StartDateID 添加一行(每次加 1),直到它匹配 EndDate。
一天被添加到 StartDateID 直到它匹配 EndDateID,此时我们停止复制。
这有意义吗?
我玩过 CTE,但一无所获。
使用递归 CTE。假设这些列实际上是日期:
with cte as (
select ID, StartDateID, EndDateID
from t
union all
select id, dateadd(day, 1, startdateid), enddateid
from cte
where startdateid < enddateid
)
select *
from cte;
如果列不是日期,我建议转换它们:
with cte as (
select ID, convert(date, StartDateID) as startdate, convert(date, EndDateID) as enddate
from t
union all
select id, dateadd(day, 1, startdate), enddate
from cte
where startdate < enddate
)
select *
from cte;
Here 是一个 db<>fiddle.
如果您的跨度可以超过 100 天,那么您需要在查询中添加 OPTION (MAXRECURSION 0)
。
表 1:
ID|StartDateID|EndDateID 468|20200101|20200104 534|20200103|20200104 123|20200106|20200108
要求输出:
ID|StartDateID|EndDateID 468|20200101|20200104 468|20200102|20200104 468|20200103|20200104 468|20200104|20200104 534|20200103|20200104 534|20200104|20200104 123|20200106|20200108 123|20200107|20200108 123|20200108|20200108
如果解释不当,我们深表歉意。表 1 列出了任务完成的开始和结束日期。每个 ID 都是一个唯一的条目。
我需要为每个 StartDateID 添加一行(每次加 1),直到它匹配 EndDate。
一天被添加到 StartDateID 直到它匹配 EndDateID,此时我们停止复制。
这有意义吗?
我玩过 CTE,但一无所获。
使用递归 CTE。假设这些列实际上是日期:
with cte as (
select ID, StartDateID, EndDateID
from t
union all
select id, dateadd(day, 1, startdateid), enddateid
from cte
where startdateid < enddateid
)
select *
from cte;
如果列不是日期,我建议转换它们:
with cte as (
select ID, convert(date, StartDateID) as startdate, convert(date, EndDateID) as enddate
from t
union all
select id, dateadd(day, 1, startdate), enddate
from cte
where startdate < enddate
)
select *
from cte;
Here 是一个 db<>fiddle.
如果您的跨度可以超过 100 天,那么您需要在查询中添加 OPTION (MAXRECURSION 0)
。