Get a list of dates between two dates

后端 未结 20 2151
醉梦人生
醉梦人生 2020-11-22 00:26

Using standard mysql functions is there a way to write a query that will return a list of days between two dates.

eg given 2009-01-01 and 2009-01-13 it would return

20条回答
  •  梦毁少年i
    2020-11-22 01:15

    Typically one would use an auxiliary numbers table you usually keep around for just this purpose with some variation on this:

    SELECT *
    FROM (
        SELECT DATEADD(d, number - 1, '2009-01-01') AS dt
        FROM Numbers
        WHERE number BETWEEN 1 AND DATEDIFF(d, '2009-01-01', '2009-01-13') + 1
    ) AS DateRange
    LEFT JOIN YourStuff
        ON DateRange.dt = YourStuff.DateColumn
    

    I've seen variations with table-valued functions, etc.

    You can also keep a permanent list of dates. We have that in our data warehouse as well as a list of times of day.

提交回复
热议问题