Skip to content
Advertisement

SQL: Getting Missing Date Values and Copy Data to Those New Dates

So this seems somewhat weird, but this use case came up, and I have been somewhat struggling trying to figure out how to come about a solution. Let’s say I have this data set:

date value1 value2
2020-01-01 50 2
2020-01-04 23 5
2020-01-07 14 8

My goal is to try and fill in the gap between the two dates while copying whatever values were from the date before it. So for example, the data output I would want is:

date value1 value2
2020-01-01 50 2
2020-01-02 50 2
2020-01-03 50 2
2020-01-04 23 5
2020-01-05 23 5
2020-01-06 23 5
2020-01-07 14 8

Not sure if this is something I can do with SQL but would definitely take any suggestions.

Advertisement

Answer

One approach is to use the window function lead() in concert with an ad-hoc tally table if you don’t have a calendar table (highly suggested).

Example

Results

EDIT: If you have a calendar table

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement