SQL Server – Generating Time Series Based on Existing Table

sql server

I have a table that has something like this:

|    Zip    |     Population    |
+-----------+-------------------+
|    00001  |     100           |
|    00002  |     200           |
|    00003  |     250           |

and so on. I would like to generate a new table from the above table which looks something like this:

|    Date       |    Zip    |     Population    |
+---------------+-----------+-------------------+
|    01-01-2016 |   00001   |     100           |
|    01-02-2016 |   00001   |     100           |
|    01-03-2016 |   00001   |     100           |
|    ...        |   00001   |     100           |
|    31-12-2016 |   00001   |     100           |
|    01-01-2016 |   00002   |     200           |
|    01-02-2016 |   00002   |     200           |
|    01-03-2016 |   00002   |     200           |
|    ...        |   00002   |     200           |
|    31-12-2016 |   00002   |     200           |

and so on for all the rows in the original table at the top.

I have found a way to generate dates between a specific range (e.g., as outlined here). I also think that I should use LEFT JOIN to achieve that?? I'm fairly new to SQL (or SQL Server, which is what I'm using at the moment). If so, what should I use as the join key? If someone could guide me through the process, I'd greatly appreciate the help. 🙂 Thank you in advance for the answers!

Best Answer

Well - if you just want a quick way to do this, the following should give you what you're looking for

declare @OriginalTable table (zip varchar(5),population int)
declare @NewTable table (DateColumn date, zip varchar(5),population int)

insert into @OriginalTable values('00001',100)
insert into @OriginalTable values('00002',200)
insert into @OriginalTable values('00003',250)
declare @WorkDate Date = '2016-01-01'
declare @EndDate date = '2016-12-31'

WHILE @WorkDate <= @EndDate
BEGIN
    INSERT INTO @NewTable
    SELECT @WorkDate
        ,zip
        ,population
    FROM @OriginalTable

    SET @WorkDate = dateadd(day, 1, @WorkDate)
END

select * from @NewTable where zip='00001'