Mysql:按值频率排序行

时间:2017-04-05 20:03:15

标签: mysql

我们说我有这张桌子:

+----+------+---------+
| Id | Item | Country |
+----+------+---------+
|  1 | b123 | Austria |
|  2 | a123 | Italy   |
|  3 | b990 | Germany |
|  4 | h231 | Austria |
|  5 | y233 | France  |
|  6 | u223 | Austria |
|  7 | p022 | Spain   |
|  8 | d133 | Italy   |
|  9 | w112 | Germany |
| 10 | j991 | Austria |
+----+------+---------+

我想在该表上执行SELECT并订购Country最重复的结果。 所以预期的输出应该是:

+----+------+---------+
| Id | Item | Country |
+----+------+---------+
|  1 | b123 | Austria |
|  4 | h231 | Austria |
|  6 | u223 | Austria |
| 10 | j991 | Austria |
|  2 | a123 | Italy   |
|  8 | d133 | Italy   |
|  3 | b990 | Germany |
|  9 | w112 | Germany |
|  5 | y233 | France  |
|  7 | p022 | Spain   |
+----+------+---------+

我该怎么做?

我试过这个:

SELECT * FROM items WHERE Item != '' GROUP BY Item HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC

但是会返回这样的东西:

+----+------+---------+
| Id | Item | Country |
+----+------+---------+
|  1 | b123 | Austria |
|  8 | d133 | Italy   |
|  3 | b990 | Germany |
|  5 | y233 | France  |
|  7 | p022 | Spain   |
+----+------+---------+

2 个答案:

答案 0 :(得分:6)

A - Original table
B - Getting the counts at Country Level.

通过加入A和B,我们可以按照计数的降序对数据进行排序,并显示表格中的所有项目。

SELECT A.*
  FROM items A
INNER JOIN 
(    SELECT Country,COUNT(*) AS cnt       
      FROM items 
     WHERE Item != '' 
     GROUP BY Item 
) B
   ON A.Country = B.Country
ORDER BY B.cnt DESC,A.Country,A.Id; 

答案 1 :(得分:1)

您可以在order by中添加子查询。所以一种方法是:

select i.*
from items i
where i.item <> ''
order by (select count(*) from items i2 where i2.item = i.item) desc;

与执行group by并加入值

相比,这种方法有优点和缺点
  • 优势:它可以利用items(item)上的索引。
  • 优点:如果where子句具有高度选择性,则每行只调用一次子查询。
  • 缺点:如果where子句的选择性不高,则每行只调用一次子查询。