generate days from date range

后端 未结 29 2404
渐次进展
渐次进展 2020-11-21 05:19

I would like to run a query like

select ... as days where `date` is between \'2010-01-20\' and \'2010-01-24\'

And return data like:

29条回答
  •  北海茫月
    2020-11-21 05:59

    Using a recursive Common Table Expression (CTE), you can generate a list of dates, then select from it. Obviously you normally wouldn't want to create three million dates, so this just illustrates the possibilities. You could simply limit the date range inside the CTE and omit the where clause from the select statement using the CTE.

    with [dates] as (
        select convert(datetime, '1753-01-01') as [date] --start
        union all
        select dateadd(day, 1, [date])
        from [dates]
        where [date] < '9999-12-31' --end
    )
    select [date]
    from [dates]
    where [date] between '2013-01-01' and '2013-12-31'
    option (maxrecursion 0)
    

    On Microsoft SQL Server 2005, generating the CTE list of all possible dates took 1:08. Generating one hundred years took less than a second.

提交回复
热议问题