获得最常发生的年份

时间:2018-08-27 22:03:13

标签: mysql sql

我有一个来自MySQL Workbench中名为world的工厂数据库的下表:

表格:country

相关列:

Code char(3) PK,
IndepYear smallint(6)

我想获得大多数国家独立的年份(或年份)。我不想仅列出年份,每年列出一行。

编辑:

我找到了可行的正确解决方案。

SELECT IndepYear
FROM   (SELECT IndepYear,
               COUNT(IndepYear) AS Years
        FROM   world.country
        GROUP  BY IndepYear
        ORDER  BY Years DESC) AS T1
WHERE  Years IN (SELECT Years
                 FROM   (SELECT IndepYear,
                                COUNT(IndepYear) AS Years
                         FROM   world.country
                         GROUP  BY IndepYear
                         ORDER  BY Years DESC
                         LIMIT  1) AS T2
                 GROUP  BY IndepYear)
ORDER  BY IndepYear ASC; 

2 个答案:

答案 0 :(得分:1)

听起来您只想ORDER BY的{​​{1}}中的COUNT。别忘了,您还希望IndepYear此列,以及添加GROUP BY中的LIMIT来获得降序排列时最常出现的年份。

1

答案 1 :(得分:1)

使用聚合获取每年的计数并将其限制为HAVING子句中的最大计数。使用子查询来获取最大数量,以汇总聚合。

SELECT indepyear
       FROM country
       GROUP BY indepyear
       HAVING count(*) = (SELECT max(c)
                                 FROM (SELECT count(*) c
                                              FROM country
                                              GROUP BY indepyear) x);

SQL Fiddle