希望通过给定以下数据填充表(SQL Server 2016):开始日期(datetime),日期(int),休息日(int),重复间隔的频率(int)

数据-2018年1月1日,开启= 7,关闭= 5,频率= 10

输出:

日期
1/1/2018
1/2/2018
1/3/2018
1/4/2018
1/5/2018
1/6/2018
1/7/2018
**跳过5 **
1/13/2018
1/14/2018
1/15/2018
1/16/2018
1/17/2018
1/18/2018
1/19/2018
**跳过5 **等。创建7并跳过5 x 10


意识到这一点可以使用循环来完成,我希望有一个方便的CTE示例或其他选项。

最佳答案

您可以使用如下查询。该解决方案基于计数/数字表方法。
要了解更多信息,请通读Jeff Moden article

See live demo

declare @sd date= '01/01/2018', @on int= 7, @off int= 5, @freq int= 10;

select d
from
(
    select
        top (@freq* (@on+@off))
        d=dateadd(d,row_number() over( order by (select null))-1 ,@sd),
        flag=case when row_number() over( order by (select null))%(@on+@off) between 1 and @on then 1 else 0 end
        from sys.objects o1
        cross join sys.objects o2
)t
where flag=1

10-05 23:45