1

重複の可能性:
SQL: 各 GROUP BY グループの最初の行を選択しますか?

2 つの SQL テーブル。1 人の競技者が多くのエントリを持っています。

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

確かに、多くのクエリでこれを実行できます。私の質問は、1 つの効率的な SQL クエリで結果を取得する方法があるかどうかです。でそれを行う方法はほとんどわかりますがGROUP BY、完全ではありません。

参考までに、環境は Rails ActiveRecord と PostgreSQL です。

4

5 に答える 5

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
于 2012-12-02T21:09:33.867 に答える
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
于 2012-12-02T21:11:11.773 に答える
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こちら

私の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
于 2012-12-02T23:01:09.240 に答える
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

ここに例があります http://sqlfiddle.com/#!3/9e307/27

于 2012-12-02T21:17:22.313 に答える
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 が注文されます

于 2012-12-02T21:18:27.307 に答える