The statement works for me:
SELECT e.id, e.title, array_agg(d.start_date) date, array_agg(d.id) ids
FROM event e JOIN event_date d ON e.id = d.event_id
GROUP BY e.id
I receive the results
id | title | dates | ids |
---|---|---|---|
1 | First Event | {2022-06-05,2022-10-05} | {1,2} |
2 | Second Event | {2022-07-05} | {3} |
I want to order events by start_date. For that, I add ORDER BY d.start_date DESC
to the statement:
SELECT e.id, e.title, array_agg(d.start_date) date, array_agg(d.id) ids
FROM event e JOIN event_date d ON e.id = d.event_id
GROUP BY e.id
ORDER BY d.start_date DESC
And I receive the error message:
ERROR: column "d.start_date" must appear in the GROUP BY clause or be used in an aggregate function LINE 4: ORDER BY d.start_date DESC
I don't understand it. array_agg
is an aggregate function. How to solve this issue?