Friday, January 26, 2018

postgresql - Finding group maxes in SQL join result










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.


Answer



Here is specific postgresql way of doing this:



SELECT DISTINCT ON (c.id) c.name, e.id, e.score
FROM Contestants c
JOIN Entries e ON c.id = e.Contestant_id
ORDER BY c.id, e.score



Details about DISTINCT ON are here.



My SQLFiddle with example.



UPD To order the results by score:



SELECT *
FROM (SELECT DISTINCT ON (c.id) c.name, e.id, e.score

FROM Contestants c
JOIN Entries e ON c.id = e.Contestant_id
ORDER BY c.id, e.score) t
ORDER BY score

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...