在SQL中将日期范围拆分为按日排列的行

时间:2019-03-20 14:35:19

标签: sql-server

我有一个包含3列的表格

enter image description here

我想每天根据Promo_Period_Start和Promo_Period_End进行分组

我尝试的是以下

declare @d datetime;
set @d = getdate();

select *
from   [dbo].[T]
where  @d between Promo_Period_Start and Promo_Period_End

样本数据

enter image description here

1 个答案:

答案 0 :(得分:0)

使用递归CTE

;WITH cte AS (
    SELECT ID, Promo_Period_Start,Promo_Period_End
    FROM T
    UNION ALL
    SELECT ID, DATEADD(day, 1, Promo_Period_Start), Promo_Period_End
    FROM cte
    WHERE Promo_Period_Start < Promo_Period_End
)
SELECT * FROM cte