Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql-按时间戳和车辆id分组_Sql_Postgresql - Fatal编程技术网

Postgresql-按时间戳和车辆id分组

Postgresql-按时间戳和车辆id分组,sql,postgresql,Sql,Postgresql,我有一张有汽车记录的桌子: table: cars columns: car_id | timestamp | km_driven 我正在运行PostgreSQL 9.6 我怎样才能做到: SELECT timestamp, car_id, km_driven_within_the_hour FROM cars 我想按时间戳分组,这样每个小时记录的所有记录都会按每辆车分组,然后将该小时内行驶的公里数和该小时内行驶的公里数相加 我试过: SELECT timestamp, car_id, S

我有一张有汽车记录的桌子:

table: cars

columns:
car_id | timestamp | km_driven
我正在运行PostgreSQL 9.6

我怎样才能做到:

SELECT timestamp, car_id, km_driven_within_the_hour FROM cars
我想按时间戳分组,这样每个小时记录的所有记录都会按每辆车分组,然后将该小时内行驶的公里数和该小时内行驶的公里数相加

我试过:

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

你快到了。将时间戳替换为小时,如中所示:

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

请回答您的问题,并根据这些数据添加一些内容和预期输出。请您的问题-请勿在评论中发布代码或其他信息谢谢。但是,我希望时间戳按格式YYYY-MM-DD HH分组,并且仅显示小时,因此我无法区分日、月和年。尝试按日期分组,时间戳::时间戳,但结果是多个记录/行具有相同的小时。似乎按时间分组,时间戳,'YYYY-MM-DD HH';解决它。