【问题标题】:Get multiple months start and end date within a larger date range在更大的日期范围内获取多个月的开始和结束日期
【发布时间】:2022-02-02 12:44:39
【问题描述】:

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

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

这样做的目的是然后过滤临时表中的数据以返回每个月范围内的数据,因此对于此示例,该表将返回 5 行

【问题讨论】:

    标签: sql date range


    【解决方案1】:

    这将返回您指定的输出:

    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
    

    【讨论】:

    • @Nikita,这个查询对你有用吗?
    • 是的,非常感谢!
    • 您介意接受我的回答吗?这有点激励人们在这里互相帮助:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多