PostgreSQL,从+1小时选择输出结果

时间:2018-07-03 11:07:46

标签: sql postgresql

我有以下SQL,每小时工作GROUP BY

SELECT
CONCAT(TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), ':00:00') as time_from,
car_id,
SUM(km) as driven from car_data
group by TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), car_id
order by time_from, car_id;

我想要一个额外的输出,即time_from +1小时间隔。 我尝试过:

SELECT
CONCAT(TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), ':00:00') as time_from,
CONCAT(TO_CHAR(timestamp::timestamp + interval '1 hour', 'YYYY-MM-DD HH'), ':00:00') as time_to,
car_id,
SUM(km) as driven from car_data
group by TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), car_id
order by time_from, car_id;

但是该报告我还需要GROUP BY该字段:

ERROR:  column "car_data.time" must appear in the GROUP BY clause or be used in an aggregate function

,我不希望这样做。我怎样才能最好地将其存档?

2 个答案:

答案 0 :(得分:2)

您只需将两列添加到group by

SELECT CONCAT(TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), ':00:00') as time_from,
       CONCAT(TO_CHAR(timestamp::timestamp + interval '1 hour', 'YYYY-MM-DD HH'), ':00:00') as time_to,
       car_id,
       SUM(km) as driven 
FROM car_data
GROUP BY time_from, time_to, car_id 
ORDER BY time_from, car_id;

但是,我不会将时间戳转换为字符串。而是使用date_trunc()

SELECT date_trunc('hour', timestamp::timestamp) as time_from,
       date_trunc('hour', timestamp::timestamp) + interval '1 hour' as time_to,
       car_id,
       SUM(km) as driven 
FROM car_data
GROUP BY date_trunc('hour', timestamp::timestamp), car_id 
ORDER BY time_from, car_id;

答案 1 :(得分:2)

一种选择是将您当前的工作查询放入CTE,然后使用该查询生成所需的输出:

WITH cte AS (
    SELECT
        timestamp::timestamp AS time_from,
        car_id,
        SUM(km) AS driven
    FROM car_data
    GROUP BY timestamp::timestamp, car_id
)

SELECT
    CONCAT(TO_CHAR(time_from, 'YYYY-MM-DD HH'), ':00:00') AS time_from,
    CONCAT(TO_CHAR(time_from + interval '1 hour', 'YYYY-MM-DD HH'), ':00:00') AS time_to,
    car_id,
    driven
FROM cte
ORDER BY
    time_from, car_id;