I'm having some struggle with something that should be a simple SQL query.
This is my initial database schema:
Also prepared the example in SQLFiddle
The query I've ended up with is:
select b.ad_id, b.auction_id, max(b.amount) as max, max(b.created_at) created_at from bid b where b.user_id = '601' group by b.ad_id, b.auction_id But in the result, I need the whole row from the bid table:
select b.id, b.ad_id, b.auction_id, max(b.amount) as max, max(b.created_at) created_at from bid b where b.user_id = '601' group by b.ad_id, b.auction_id Which fails with: [42803] ERROR: column "b.id" must appear in the GROUP BY clause or be used in an aggregate function Position: 16. Cannot add the id field in the GROUP BY clause, because it will add some extra rows I don't need.
What I need is to select from the bid table the highest record (amount field) grouped by auction_id and ad_id.
I think I need to make some self inner join or subselect but right now I'm not able to write the SQL.
