MySQL Group By各种前N个数

时间:2009-10-08 12:53:55

标签: mysql group-by ranking

我有一张这样的表:

Rank      Letter
1         A
2         A
3         B
4         A
5         C
6         A
7         C
8         C
9         B
10        C 

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

Rank      Letter
1         A
2         A
3         B
5         C
7         C
9         B

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

2 个答案:

答案 0 :(得分:7)

SELECT  mo.Letter, md.Rank
FROM    (
        SELECT  DISTINCT letter
        FROM    mytable
        ) mo
JOIN    mytable md
ON      md.Letter >= mo.Letter
        AND md.Letter <= mo.Letter
        AND Rank <=
        COALESCE
                (
                (
                SELECT  Rank
                FROM    mytable mi
                WHERE   mi.letter = mo.letter
                ORDER BY
                        Rank
                LIMIT 1, 1
                ),
                0xFFFFFFFF
                )

您需要在(Letter, Rank)(按此顺序)

上建立综合索引

请注意这个结构:

md.Letter >= mo.Letter
AND md.Letter <= mo.Letter

而不仅仅是md.Letter = mo.Letter

强制Range checked for each record更有效率。

在我的博客中查看此文章:

了解更多详情。

答案 1 :(得分:2)

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 server上工作)例如

第二次尝试:

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