获取每个列值的前N个结果

时间:2012-08-24 08:41:34

标签: mysql greatest-n-per-group

我有一张这样的桌子:

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

如何获得每种的前N项?例如。 N = 2:

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

提前致谢!

1 个答案:

答案 0 :(得分:3)

这是SqlFiddle demo

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