根据日期范围创建日期和时间列



我想创建一个临时表,在那里我给它一个开始和结束日期(价格日期)。然后结果是一列中的日期和另一列中每天的小时。

它看起来像这样:

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
   .        .
   .        .
   .        .

所以似乎我想用generate_series一个小时。但不确定如何将其与日期相匹配。

这不是为我完成的:

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
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
...

使用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

相关内容

  • 没有找到相关文章

最新更新