一尘不染

MySQL Group By,每种类型的前N个

mysql

我有一张这样的桌子:

等级信
1个
2个
3个
4个
5℃
6个
7℃
8℃
9号
10摄氏度

我需要按升序排列每个字母的前2个:

等级信
1个
2个
3个
5℃
7℃
9号

我该怎么办?使用GROUP BY获得前1名非常简单,但是我似乎无法让它适用于多个条目


阅读 431

收藏
2020-05-17

共1个答案

一尘不染

select distinct rank, letter
  from table1 t2
 where rank in 
         (select top 2 rank
            from table1 t2 
           where t2.letter = t1.letter 
           order by rank)
       order by letter, rank

编辑:(我的第一次尝试将无法在MySql(Quassnoi注释)上工作,例如,我将其修改为可在sql服务器上工作)

第二次尝试:

select t.letter, t.rank
from table1 t
join (
    select t1.letter, min(t1.rank) m
    from table1 t1
    join (select t0.letter, min(t0.rank) m, count(1) c 
           from table1 t0 group by t0.letter) t2
    on t1.letter = t2.letter and ((t2.c = 1) or (t2.c > 1 and t1.rank > m))
    group by t1.letter) t3 
  on t.letter = t3.letter and t.rank <= t3.m
2020-05-17