1

我有一张这样的桌子:

+--------+--------+
|  name  |  kind  |
+--------+--------+
| cat    | animal |
| dog    | animal |
| horse  | animal |
| ant    | animal |
| bird   | animal |
| tree   | plant  |
| grass  | plant  |
| carrot | plant  |
|                 |
|     ... etc.    |
+--------+--------+

我如何获得每种类型的 Top N 项?例如 N=2:

+--------+--------+
|  name  |  kind  |
+--------+--------+
| ant    | animal |
| bird   | animal |
| carrot | plant  |
| grass  | plant  |
+--------+--------+

提前致谢!

4

1 回答 1

3

这是一个SqlFiddle 演示

select name,kind from
(

select Name,Kind,
      @i:=if(@kind=kind,@i+1,1) rn,
      @kind:=kind 
      from t, (select @i:=0,@kind:='') d 
      order by Kind,name
) t1
where t1.rn<=2
     order by Kind,name
于 2012-08-24T08:54:20.553 回答