从一段时间生成一个表,每个条目跨越一个小时

时间:2014-03-07 04:54:59

标签: sql postgresql types date-arithmetic generate-series

例如我早上8点到晚上8点 我希望桌子能够生成表格,其中逐个starttimeendtime(两列)输入:

8:00-9:00
9:00-10:00
....
19:00-20:00

就像这样。没有日期。

2 个答案:

答案 0 :(得分:1)

您可以使用generate_series功能执行此操作:

psql# select generate_series('2014-01-01 16:00'::timestamp, '2014-01-01 20:00'::timestamp, '1 hour');
   generate_series   
---------------------
 2014-01-01 16:00:00
 2014-01-01 17:00:00
 2014-01-01 18:00:00
 2014-01-01 19:00:00
 2014-01-01 20:00:00
(5 rows)

然后你可以使用:

SELECT
    t AS starttime,
    t + INTERVAL '1 hour' as endtime
FROM
    GENERATE_SERIES(
        '2014-01-01 16:00'::TIMESTAMP,
        '2014-01-01 20:00'::TIMESTAMP,
        '1 hour'
    ) AS t

获取开始和结束时间。

或者,为了获得时间,您可以使用:

SELECT
    '08:00'::time + (t || ' hours')::interval as starttime,
    '08:00'::time + ((t + 1)::text || ' hours')::interval as endtime
FROM
    GENERATE_SERIES(0, 12) AS t

答案 1 :(得分:0)

更简单,使用带有虚拟日期组件的完整时间戳并转换为time

SELECT t::time  AS starttime
     , t::time + interval '1h' AS endtime
FROM   generate_series('2000-1-1 08:00'::timestamp
                     , '2000-1-1 19:00'::timestamp
                     , interval '1h') t;

text列的内容相同:

SELECT to_char(t, 'HH24:MI') AS starttime
     , to_char(t + interval '1h', 'HH24:MI') AS endtime
FROM   generate_series('2000-1-1 08:00'::timestamp
                     , '2000-1-1 19:00'::timestamp
                     , interval '1h') t;