So I know this is a pretty dumb question, however (as the rather lengthily title says) I would like to know how do the following:
I have a table like this:
ID Foo Bar Blagh
----------------
1 10 20 30
2 10 5 1
3 20 50 40
4 20 75 12
I want to group by Foo, then pull out rows with minimum Bar, i.e. I want the following:
ID Foo Bar Blagh
----------------
2 10 5 1
3 20 50 40
I can’t for the life of me work out the correct SQL to retrieve this. I want something like:
SELECT ID, Foo, Bar, Blagh
FROM Table
GROUP BY Foo
HAVING(MIN(Bar))
However this clearly doesn’t work as that is completely invalid HAVING syntax and ID, Foo, Bar and Blagh are not aggregated.
What am I doing wrong?
This is almost exactly the same question, but it has some answers!
Here’s me mocking up your table:
Then you can do an anonymous inner join to get the data you want.
EDIT Adam Robinson has helpfully pointed out that “this solution has the potential to return multiple rows when the minimum value of Bar is duplicated, and eliminates any value of foo where bar is
null“Depending upon your usecase, duplicate values where Bar is duplicated might be valid – if you wanted to find all values in Borg where Bar was minimal, then having both results seems the way to go.
If you need to capture
NULLsin the field across which you are aggregating (by MIN in this case), then you couldcoalescethe NULL with an acceptably high (or low) value (this is a hack):Or you could go for a UNION and attach all such values to the bottom of your resultset.
The latter will not group values in @Borg with the same
Foovalue because it doesn’t know how to select between them.