Get a list of dates between two dates using a function

前端 未结 21 1330
天涯浪人
天涯浪人 2020-11-22 06:25

My question is similar to this MySQL question, but intended for SQL Server:

Is there a function or a query that will return a list of days between two dates? For exa

21条回答
  •  耶瑟儿~
    2020-11-22 07:04

    This query works on Microsoft SQL Server.

    select distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate
           from (
                 SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
                 FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
                        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
                        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
                      (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
           ) a
           where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)
           order by aDate asc;
    

    Now let's look at how it works.

    The inner query merely returns a list of integers from 0 to 9999. It will give us a range of 10,000 values for calculating dates. You can get more dates by adding rows for ten_thousands and hundred_thousands and so forth.

    SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
             FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
                  (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
       ) a;
    

    This part converts the string to a date and adds a number to it from the inner query.

    cast('2010-01-01' as datetime) + ( a.v / 10 )
    

    Then we convert the result into the format you want. This is also the column name!

    format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' )
    

    Next we extract only the distinct values and give the column name an alias of aDate.

    distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate
    

    We use the where clause to filter in only dates within the range you want. Notice that we use the column name here since SQL Server does not accept the column alias, aDate, within the where clause.

    where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)
    

    Lastly, we sort the results.

       order by aDate asc;
    

提交回复
热议问题