2017-04-05 96 views
4

令行比方說,我有這個表: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 | 
+----+------+---------+ 
+1

您是否嘗試在'SELECT'之後添加'DISTINCT'關鍵字? – Sablefoste

回答

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

您可以在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子句不具有高度選擇性,則每行僅調用子查詢一次。