generate days from date range

后端 未结 29 3090
渐次进展
渐次进展 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 06:11

    Generate dates between two date fields

    If you are aware with SQL CTE query, then this solution will helps you to solve your question

    Here is example

    We have dates in one table

    Table Name: “testdate”

    STARTDATE   ENDDATE
    10/24/2012  10/24/2012
    10/27/2012  10/29/2012
    10/30/2012  10/30/2012
    

    Require Result:

    STARTDATE
    10/24/2012
    10/27/2012
    10/28/2012
    10/29/2012
    10/30/2012
    

    Solution:

    WITH CTE AS
      (SELECT DISTINCT convert(varchar(10),StartTime, 101) AS StartTime,
                       datediff(dd,StartTime, endTime) AS diff
       FROM dbo.testdate
       UNION ALL SELECT StartTime,
                        diff - 1 AS diff
       FROM CTE
       WHERE diff<> 0)
    SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime
    FROM CTE
    

    Explanation: CTE Recursive query explanation

    • First part of query:

      SELECT DISTINCT convert(varchar(10), StartTime, 101) AS StartTime, datediff(dd, StartTime, endTime) AS diff FROM dbo.testdate

      Explanation: firstcolumn is “startdate”, second column is difference of start and end date in days and it will be consider as “diff” column

    • Second part of query:

      UNION ALL SELECT StartTime, diff-1 AS diff FROM CTE WHERE diff<>0

      Explanation: Union all will inherit result of above query until result goes null, So “StartTime” result is inherit from generated CTE query, and from diff, decrease - 1, so its looks like 3, 2, and 1 until 0

    For example

    STARTDATE   DIFF
    10/24/2012  0
    10/27/2012  0
    10/27/2012  1
    10/27/2012  2
    10/30/2012  0
    

    Result Specification

    STARTDATE       Specification
    10/24/2012  --> From Record 1
    10/27/2012  --> From Record 2
    10/27/2012  --> From Record 2
    10/27/2012  --> From Record 2
    10/30/2012  --> From Record 3
    
    • 3rd Part of Query

      SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime FROM CTE

      It will add day “diff” in “startdate” so result should be as below

    Result

    STARTDATE
    10/24/2012
    10/27/2012
    10/28/2012
    10/29/2012
    10/30/2012
    

提交回复
热议问题