在MySQL上为每个组选择一个记录

时间:2019-02-26 23:16:01

标签: mysql greatest-n-per-group

我只想每个班上有1个记录,是最小的学生?

select e.`cname`, s.`sname`
from `Nguy3524`.`enrolled` e, `Nguy3524`.`student` s
where e.`snum` = s.`snum`
and e.`snum` in (
                 Select g1.`snum`
                  from `Nguy3524`.`grade` g1
                  where g1.`score` in (select max(g2.`score`) 
                  from `Nguy3524`.`grade` g2 where g1.`cname` = g2.`cname` ))
order by s.`age`

现在它返回带有多个sname的cname,但我只是eacch组的第一条记录。

1 个答案:

答案 0 :(得分:0)

如果使用的是MySql 8,则可以使用row_number方法

select * from (
    select e.`cname`, s.`sname`,
      row_number() over (partition by cname order by age) rn 
    from `Nguy3524`.`enrolled` e, `Nguy3524`.`student` s
    where e.`snum` = s.`snum`
    and e.`snum` in (
                     Select g1.`snum`
                      from `Nguy3524`.`grade` g1
                      where g1.`score` in (select max(g2.`score`) 
                      from `Nguy3524`.`grade` g2 where g1.`cname` = g2.`cname` ))
) t
where rn = 1
order by s.`age`