在更大的日期范围内获取多个月的开始和结束日期

Get multiple months start and end date within a larger date range

所以我挣扎的是假设我输入了 1 月 1 日的开始日期和 5 月 31 日的结束日期,我需要 returned 是:

Jan Start Date, Jan end Date
Feb start Date, Feb End date
March start Date, March End date
April start Date, April End date
May start Date, May End date

这样做的目的是将临时 table 中的数据过滤到 return 每个月范围内的数据,因此对于此示例,table 将 return 5 行

这 returns 您指定的输出:

declare @start DATE = '2022-01-01'
declare @end DATE = '2022-05-31'

;with months (date)
AS
(
    SELECT @start
    UNION ALL
    SELECT DATEADD(month, 1, date)
    from months
    where DATEADD(month, 1, date) < @end
)
select     [Start Date] = date,
           [End Date]   = DATEADD(day, -1, DATEADD(month,1, date))
           
from months