这是一张桌子
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
感谢您的帮助
答案 0 :(得分:1)
这在“传统” 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