Postgresql - GROUP BY timestamp AND car_id
Postgresql - GROUP BY timestamp AND car_id
I've got a table with car records:
table: cars
columns:
car_id | timestamp | km_driven
I'm running PostgreSQL 9.6
.
PostgreSQL 9.6
How can I do a:
SELECT timestamp, car_id, km_driven_within_the_hour FROM cars
I want to GROUP BY
my timestamp
so all records recorded with each hour is grouped by each car, and then have km_driven_within_the_hour
SUM
'ed togehter within that hour.
GROUP BY
timestamp
km_driven_within_the_hour
SUM
I've tried:
SELECT timestamp, car_id, SUM(km_driven) AS km_driven_within_the_hour
FROM cars
GROUP BY trunc(EXTRACT(hour from timestamp)), car_id
Gives me error:
ERROR: function pg_catalog.date_part(unknown, text) does not exist
And casting timestamp:
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
Gives me:
ERROR: column "cars.timestamp" must appear in the GROUP BY clause or be used in an aggregate function
1 Answer
1
You're almost there. Replace the timestamp
by the hour, as in:
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
Thank you. I would like, however, the timestamp to be
GROUP BY
the format YYYY-MM-DD HH
and with this it only seems hour
is shown, so I cannot differ between day, month and year.– Alfred Balle
Jul 3 at 9:16
GROUP BY
YYYY-MM-DD HH
hour
Tried
group by date_trunc('hour', timestamp::timestamp)
but that results in multiple records/lines with same hour.– Alfred Balle
Jul 3 at 10:55
group by date_trunc('hour', timestamp::timestamp)
Seems
group by TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH');
solves it.– Alfred Balle
Jul 3 at 11:02
group by TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH');
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please edit your question and add some sample data and the expected output based on that data. Formatted text please, no screen shots. (edit your question - do not post code or additional information in comments)
– a_horse_with_no_name
Jul 2 at 13:18