两个SQL表。一位参赛者有很多参赛作品:
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
低分获胜。需要检索按分数排序的所有参赛者的当前最佳分数:
Best Entries Report
Name Entry_Id Score
---- -------- -----
Fred 5 19
Irving 2 22
Grizelda 4 123
我当然可以通过许多查询完成此操作。我的问题是,是否有办法通过一个有效的SQL查询获得结果。我几乎可以看到如何使用GROUP BY
,但不完全。
如果它是相关的,环境是Rails ActiveRecord和PostgreSQL。
答案 0 :(得分:1)
最简单的方法是使用排名功能:
select name, Entry_id, score
from (select e.*, c.name,
row_number() over (partition by e.contestant_id order by score) as seqnum
from entries e join
contestants c
on c.Contestant_id = c.id
) ec
where seqnum = 1
答案 1 :(得分:1)
我对PostgreSQL并不熟悉,但这些内容应该有效:
SELECT c.*, s.Score
FROM Contestants c
JOIN (SELECT MIN(Score) Score, Contestant_Id FROM Entries GROUP BY Contestant_Id) s
ON c.Id=s.Contestant_Id
答案 2 :(得分:1)
其中一个解决方案是
select min(e.score),c.name,c.id from entries e
inner join contestants c on e.contestant_id = c.id
group by e.contestant_id,c.name,c.id
答案 3 :(得分:1)
这个简单的查询应该可以解决问题..
Select contestants.name as name, entries.id as entry_id, MIN(entries.score) as score
FROM entries
JOIN contestants ON contestants.id = entries.contestant_id
GROUP BY name
ORDER BY score
这会抓住每个参赛者的最低分数并命令他们ASC
答案 4 :(得分:1)
这是具体的postgresql方式:
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
DISTINCT ON
的详细信息为here。
我的SQLFiddle示例。
UPD按分数订购结果:
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