これが表です
ID | Player | Position | Points
1 | Ryan | QB | 75
2 | Matt | RB | 80
3 | Mike | WR | 66
4 | Jay | QB | 71
6 | Alvin | TE | 73
7 | Adrian | TE | 84
8 | Hill | WR | 71
9 | Charles| RB | 53
10 | Bell | WR | 87
11 | Rob | TE | 49
12 | Alex | RB | 92
13 | Drew | QB | 84
14 | Mack | TE | 59
15 | Nick | WR | 33
ポイントが最も高いプレイヤーのポジションにいるすべてのプレイヤーと、他のポジションの上位2人のプレイヤーを報告したいと思います。この例では、「Alex」が最も高いポイントを持ち、「RB」です。そこで、「RB」の全選手と「QB」「TE」「WR」の上位2名を報告し、各グループでポイント順に並べていきたい。私はsqlite3を使用しています。私はPythonとsqlite3を使用してプログラムでこれを行うことができますが、これはsqlを使用してのみ行うことができるかどうか疑問に思いました
ID | Player | Position | Points
12 | Alex | RB | 92
2 | Matt | RB | 80
9 | Charles| RB | 53
13 | Drew | QB | 84
1 | Ryan | QB | 75
10 | Bell | WR | 87
8 | Hill | WR | 71
7 | Adrian | TE | 84
6 | Alvin | TE | 73
ご協力いただきありがとうございます
これは「従来の」SQLiteでは注意が必要です。私はお勧めしunion all
ます:
with top1 as (
select t.*
from t
order by points desc
limit 1
)
select t.*
from t
where t.position = (select t1.position from top1 t1)
union all
select t.*
from t
where t.position <> (select t1.position from top1 t1) and
(select count(*)
from t t2
where t2.position = t.position and
t2.points >= t.points
) <= 2;
これは、points
値が一意であることを前提としています。SQLiteではネクタイを扱うのがはるかに困難です。
SQLiteバージョン3.25.0へのアップグレードを検討するか、別のデータベースを使用することをお勧めします。このようなクエリは、ISO / ANSI標準ウィンドウ関数を使用するとはるかに簡単になります。
ウィンドウ関数を使用すると、次のようになります。
select t.*
from (select t.*,
row_number() over (partition by position order by points desc) as seqnum,
first_value(position) over (order by points desc) as first_position
from t
) t
where seqnum <= 2 or position = first_position
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加