【问题标题】:Split dates into quarters based on start and end date根据开始日期和结束日期将日期分成季度
【发布时间】:2021-07-21 23:12:37
【问题描述】:

我想根据给定的开始和结束日期拆分季度。 我有下表:

表1

ID start_date end_date No. of Quarters
1 01-01-2017 01-01-2018 4
2 01-04-2017 01-10-2018 7

因此,结果表应根据季度数和结束日期拆分日期。 结果表应如下所示:

表2

ID Quarterly Start Date
1 01-01-2017
1 01-04-2017
1 01-07-2017
1 01-10-2017
2 01-04-2017
2 01-07-2017
2 01-10-2017
2 01-01-2018
2 01-04-2018
2 01-07-2018
2 01-10-2018

我在 stackoverflow 上找到了一个解决方案

declare @startDate datetime
declare @endDate datetime

select
    @startDate= ET.start_date,
    @endDate= ET.end_date    
from
    table1

;With cte
As
( Select @startDate date1
Union All
Select DateAdd(Month,3,date1)   From cte where date1 < @endDate 
) select cast(cast( Year(date1)*10000 + MONTH(date1)*100 + 1 as 
varchar(255)) as date) quarterlyDates From cte

由于我是 sql 新手,因此无法针对我的问题自定义它。 有人可以推荐一种方法吗?谢谢!

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案1】:

    如果我理解正确,递归 CTE 将如下所示:

    with cte as (
          select id, start_date, num_quarters
          from t
          union all
          select id, dateadd(month, 3, start_date), num_quarters - 1
          from cte
          where num_quarters > 1
         )
    select *
    from cte;
    

    Here 是一个 dbfiddle。

    【讨论】: