otterdog2000
otterdog2000

Reputation: 363

Create date and hour columns from date range

I want to create a temp table where I give it a starting and ending date (pricedate). Then the results are those dates in one column and the hour of each day in the other column.

It would look like this:

date       hour
------------------
1/17/19     1
1/17/19     2
1/17/19     3
   .        .
   .        .
1/17/19    24
1/18/19     1
1/18/19     2
1/18/19     3
   .        .
   .        .
   .        .

So it seems like I want to use generate_series for the hour. But not sure how to match that up with dates.

This is not getting it done for me:

WITH hrs AS (SELECT * FROM generate_series(1,24)),
pricedate AS (SELECT * FROM generate_series('2018-01-24', '2018-01-26', interval '1 day'))


SELECT pricedate, hrs
WHERE pricedate BETWEEN '2018-01-24' AND '2018-01-26'
ORDER BY pricedate, hour

Upvotes: 3

Views: 498

Answers (2)

klin
klin

Reputation: 121889

select d::date as date, extract(hour from d)::int+ 1 as hour
from generate_series('2018-01-24', '2018-01-26 23:00', interval '1 hour') s(d)

    date    | hour 
------------+------
 2018-01-24 |    1
 2018-01-24 |    2
 2018-01-24 |    3
 2018-01-24 |    4
...

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1271151

Use a cross join:

WITH hrs AS (
       SELECT gs.hr
       FROM generate_series(1,24) gs(hr)
      ),
      pricedate AS (
       SELECT gs.priceate
       FROM generate_series('2018-01-24', '2018-01-26', interval '1 day') gs(pricedate)
      )
SELECT pricedate.pricedate, hrs.hr
FROM hrs CROSS JOIN pricedate
WHERE pricedate.pricedate BETWEEN '2018-01-24' AND '2018-01-26'
ORDER BY pricedate.pricedate, hrs.hour

Upvotes: 2

Related Questions