I have such table and need table 2 result. I am trying to select rows with max date grouped by project_id and ordered by id. And result table must have id column. Tried such request:
SELECT MAX(charges.id) as id,
"charges"."profile_id", MAX(failed_at) AS failed_at
FROM "charges"
GROUP BY "charges"."profile_id"
ORDER BY "charges"."id" ASC
And have error:
ERROR: column "charges.id" must appear in the GROUP BY clause or be used in an aggregate function)
Example table
id | profile_id | failed_at |
---|---|---|
1 | 1 | 01.01.2021 |
2 | 1 | 01.02.2021 |
3 | 1 | 01.03.2021 |
4 | 2 | 01.06.2021 |
5 | 2 | 01.05.2021 |
6 | 2 | 01.04.2021 |
Needed result
id | profile_id | failed_at |
---|---|---|
3 | 1 | 01.03.2021 |
4 | 2 | 01.06.2021 |
CodePudding user response:
SELECT charges.*
FROM charges
INNER JOIN
(
SELECT
profile_id,
MAX(charges.failed_at) AS MaxFailed_at
FROM charges
GROUP BY profile_id
) AS xQ ON charges.profile_id = xQ.profile_id AND charges.failed_at = xQ.MaxFailed_at