0

I'm having some struggle with something that should be a simple SQL query.

This is my initial database schema:

![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.

2
  • Please describe the logic you want to implement. Commented Dec 5, 2019 at 15:41
  • Updated with more info Commented Dec 5, 2019 at 15:48

2 Answers 2

2

What I need is to select from the bid table the highest record (amount field) grouped by auction_id and ad_id

Take a look at DISTINCT ON in the docs. Your desired result would be obtained by the following query.

select DISTINCT ON (b.ad_id, b.auction_id) b.id, b.ad_id, b.auction_id, b.amount b.created_at from bid b where b.user_id = '601' ORDER BY b.ad_id, b.auction_id, b.amount DESC 
Sign up to request clarification or add additional context in comments.

1 Comment

This looks like what I need. Please let me check. Gave you +1
0

If you want the most recent row for each auction for the given user, then you can use a correlated subquery to filter:

select b.* from bid b where b.user_id = '601' and b.created_at = (select max(b2.created_at) from bid b2 where b2.auction_id = b.auction_id and b2.user_id = b.user_id ); 

This seems like a sensible interpretation of what you want. I don't know if ad_id is needed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.