假设我有这张表:
+----+------+---------+
| 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 |
+----+------+---------+
Run Code Online (Sandbox Code Playgroud)
我想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 |
+----+------+---------+
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我试过这个:
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 |
+----+------+---------+
Run Code Online (Sandbox Code Playgroud)
A - Original table
B - Getting the counts at Country Level.
Run Code Online (Sandbox Code Playgroud)
通过连接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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |