我有一张有汽车记录的桌子:
table: cars
columns:
car_id | timestamp | km_driven
我正在运行PostgreSQL 9.6
。
我该怎么做:
SELECT timestamp, car_id, km_driven_within_the_hour FROM cars
我想GROUP BY
我的timestamp
,以便将每小时记录的所有记录按每辆车分组,然后在该小时内将km_driven_within_the_hour
SUM
合并在一起。
我尝试过:
SELECT timestamp, car_id, SUM(km_driven) AS km_driven_within_the_hour
FROM cars
GROUP BY trunc(EXTRACT(hour from timestamp)), car_id
给我错误:
ERROR: function pg_catalog.date_part(unknown, text) does not exist
以及投放时间戳记:
SELECT timestamp, car_id, SUM(km_driven) AS km_driven_within_the_hour
FROM cars
GROUP BY trunc(EXTRACT(hour from timestamp::timestamp)), car_id
给我:
ERROR: column "cars.timestamp" must appear in the GROUP BY clause or be used in an aggregate function
答案 0 :(得分:1)
您快到了。按小时替换timestamp
,如下所示:
SELECT
trunc(EXTRACT(hour from timestamp::timestamp)),
car_id,
SUM(km_driven) AS km_driven_within_the_hour
FROM cars
GROUP BY trunc(EXTRACT(hour from timestamp::timestamp)), car_id