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

它看起来像这样:

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

最佳答案

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

关于sql - 从日期范围创建日期和小时列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54242450/

10-13 04:48