在 SQl 中按 GROUP 限制 (postgresql)

LIMIT by GROUP in SQl (postgresql)

下面是我的 table 学生(原始有 100K+ 行,只显示一组):

id name class marks
1 Ryan 5 8
2 Max 5 7
3 Max1 5 10
4 Ryan1 6 8
5 Max2 6 10
6 Ryan2 6 7
7 Ryan3 7 8
8 Max3 7 10
9 Ryan4 7 7

我想为每个 class(5 和 7)获取两行标记 <= 10,也按 class 排序,标记 ASC

因此,预期结果将是:-

id name class marks
1 Ryan 5 8
3 Max1 5 10
7 Ryan3 7 8
8 Max3 7 10

为了执行下面我试过:-

SELECT DISTINCT t_out.class, t_top.marks, t_top.name 
FROM students t_out 
  JOIN LATERAL (
    select * 
    from students t_in 
    where t_in.class = t_out.class 
    ORDER BY t_in.id ASC
  ) t_top ON TRUE 
WHERE t_top.marks <= 10 
 AND (t_out.class = 5 OR t_out.class = 7) 
ORDER BY t_top.marks DESC LIMIT 2;

Result on original database:- it's loading since long time

Result on sample :- Error: near line 20: near "(": syntax error

你会使用 row_number():

select s.*
from (select s.*,
             row_number() over (partition by class order by marks desc) as seqnum
      from students s
      where marks < 10 and class in (5, 7)
     ) s
where seqnum <= 2
order by class, marks;

注意:您的问题有点令人费解。您似乎想要两行,每个 class 的 最高 标记按标记降序排列。

编辑:

根据您的评论:

select s.*
from (select s.*,
             row_number() over (partition by class order by marks desc) as seqnum,
             count(*) over (partition by class) as cnt
      from students s
      where marks < 10 
     ) s
where seqnum <= 2 and cnt >= 2
order by class, marks;