Finding group maxes in SQL join result
Posted
by
Gene
on Stack Overflow
See other posts from Stack Overflow
or by Gene
Published on 2012-12-02T20:51:49Z
Indexed on
2012/12/02
23:04 UTC
Read the original article
Hit count: 193
Two SQL tables. One contestant has many entries:
Contestants Entries
Id Name Id Contestant_Id Score
-- ---- -- ------------- -----
1 Fred 1 3 100
2 Mary 2 3 22
3 Irving 3 1 888
4 Grizelda 4 4 123
5 1 19
6 3 50
Low score wins. Need to retrieve current best scores of all contestants ordered by score:
Best Entries Report
Name Entry_Id Score
---- -------- -----
Fred 5 19
Irving 2 22
Grizelda 4 123
I can certainly get this done with many queries. My question is whether there's a way to get the result with one, efficient SQL query. I can almost see how to do it with GROUP BY
, but not quite.
In case it's relevant, the environment is Rails ActiveRecord and PostgreSQL.
© Stack Overflow or respective owner