在mysql中使用order by和group by

时间:2016-05-03 06:42:57

标签: mysql

有一个名为sample的表,其中包含列名和游戏。

name      games  
a        tennis  
b        tennis  
c        football  
d        shuttle  
e        basketball  
f        football  
g        football 

等等。

我需要fisrt 2最常玩游戏和前2个最少玩游戏的列表。 如何一起使用group by和order?

2 个答案:

答案 0 :(得分:2)

如果您想要点名,您可以这样做

select count(*)  as num, games from sample 
group by games 
order by  num

为第二场

select count(*)   as num, games from sample 
group by games 
order by  num limit 2

最后两个

select count(*)  as num, games from sample 
group by games 
order by  num DESC limit 2

答案 1 :(得分:0)

select games, count(1) value
from sample
group by games order by value desc limit 2
UNION ALL
select games, count(1) value
from sample
group by games order by value limit 2