我想创建一个临时表,在其中指定开始和结束日期(标价)。然后结果是一列中的日期和另一列中的每天的小时。
它看起来像这样:
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
答案 0 :(得分:2)
使用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
答案 1 :(得分:2)
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
...