按组分获得十大价值

时间:2014-03-14 03:10:40

标签: mysql

我有以下表格:

ID    |State|# of Orders
-----------------------------
1001  | CA  |   39
1002  | CA  |   100
1003  | CA  |   32
1004  | CA  |   9
1005  | IL  |   60
1006  | IL  |   67
1007  | IL  |   47
1008  | IL  |   35
1009  | MA  |   67
1010  | MA  |   23
1011  | MA  |   3
1012  | MA  |   38
1013  | MO  |   9 
1014  | MO  |   45
1015  | MO  |   75
1016  | MO  |   8
1017  | AZ  |   48
1018  | AZ  |   100
1019  | AZ  |   75
1020  | AZ  |   72

如何获得一个结果,该结果返回每个具有最高订单数量的状态的前5个ID?

select ID, State, # of Orders
from table
???

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您可以在每个州的一行上完成所有操作,则可以执行以下操作:

select state, substring_index(group_concat(id order by NumOrders desc), ',', 5) as top5
from table t
group by state;

你也可以每个状态一行,假设没有重复:

select id, state, numorders
from table t
where (select count(*)
       from table t2
       where t2.state = t.state and
             (t2.numorders > numorders or
              t2.numorders = t.numorders and t2.id <= t.id
             )
      ) <= 5;