Get a list of dates between two dates

后端 未结 20 2098
醉梦人生
醉梦人生 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条回答
  • 2020-11-22 01:14
    select * from table_name where col_Date between '2011/02/25' AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))
    

    Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.

    output:
    2011/02/25
    2011/02/26
    2011/02/27

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题