2013-11-01 35 views
0

我有一個單獨的表'國家'(具有SQLWorkbench演示版),屬性爲'name'和'IndepYear'。基本SQL。有沒有更好的方法來使用聚合函數?

我想找到更多的國家成爲獨立的一年,我對他們的名字不感興趣。

此查詢適用。

SELECT Nest.IndepYear, Nest.conta 
    FROM (Select IndepYear,count(IndepYear) AS conta 
    FROM country GROUP BY IndepYear) Nest 
    WHERE Nest.conta = (Select max(conta) FROM (SELECT IndepYear,count(IndepYear) AS conta 
    FROM country GROUP BY IndepYear)Nest2) 

輸出

IndepYear Conta 
1960  18 
1991  18 

有沒有更聰明,更可讀或比較有效的方法來做到這一點?

編輯:謝謝你的答案到目前爲止,但我感興趣的是得到頂部結果。我的意思是隻獲得所有前n行和那些行。

回答

0

這遠非完美,但可以給你如何提高你的查詢的一些想法:

select IndepYear, count(*) 
from country 
group by IndepYear 
having count(*) = (
    select count(*) from country group by IndepYear order by count(*) desc limit 1 
) 
+0

是的,它的工作。謝謝。如果使用mySQLWorkbench中的相同演示數據庫的任何人都想嘗試使用'count(IndepYear)'''count(*)',因爲有很多NULL值。 –

0

如果我正確理解你的問題,下面的SQL應該做的伎倆:

SELECT IndepYear, count(IndepYear) conta 
FROM Countries 
GROUP BY IndepYear 
ORDER By count(IndepYear) DESC 

請參閱SQL Fiddle以獲取完整的解決方案。

相關問題