简体   繁体   中英

How to Create table with Dates in range defined by table with start date inputs

I am trying to create a dates table in SQL based on a set of inputs, but I haven't been able to figure it out.

I am receiving in SQL inputs as below:

This table:

Date Value
2022-01-01 5
2022-07-12 10
2022-11-15 3

A Start Date = 2022-01-01 A stop Date = 2022-12-01

I need to get a table as below starting from Start Date until Stop Date, assiging each correspondent number based on the initial table to each date in that period:

Date Value
2022-01-01 5
2022-01-02 5
2022-01-03 5
2022-01-04 5
. 5
. 5
. 5
2022-07-09 5
2022-07-10 5
2022-07-11 5
2022-07-12 10
2022-07-13 10
2022-07-14 10
. 10
. 10
2022-11-13 10
2022-11-14 10
2022-11-15 3
2022-11-16 3
2022-11-17 3
2022-11-18 3

How can I do that?

Thanks.

Using the window function lead() over() in concert with an ad-hoc tally table

Example

Select Date = dateadd(DAY,N,A.Date)
      ,A.Value
 From  ( 
        Select *
              ,nDays = datediff(DAY,Date,lead(Date,1,dateadd(day,1,'2022-12-01')) over (order by date))
         From  YourTable
       ) A
 Join ( Select Top 1000 N=-1+Row_Number() Over (Order By (Select NULL)) From master..spt_values n1, master..spt_values n2 ) B
   on N<NDays
 Order by Date

Results

Date        Value
2022-01-01  5
2022-01-02  5
2022-01-03  5
2022-01-04  5
2022-01-05  5
...
2022-07-10  5
2022-07-11  5
2022-07-12  10
2022-07-13  10
2022-07-14  10
...
2022-11-12  10
2022-11-13  10
2022-11-14  10
2022-11-15  3
2022-11-16  3
2022-11-17  3
...
2022-11-30  3
2022-12-01  3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM