我有一个表“Country”(作为 SQLWorkbench 的演示提供的表),其属性为:“name”和“IndepYear”。
我想找到有更多国家独立的年份,我对它们的名字不感兴趣。
此查询有效。
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 行和仅这些行。
最佳答案
这远非完美,但可能会给您一些关于如何改进查询的想法:
select IndepYear, count(*)
from country
group by IndepYear
having count(*) = (
select count(*) from country group by IndepYear order by count(*) desc limit 1
)
关于mysql - 基本 SQL。有没有更好的方法来使用聚合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19731732/