选择从COUNT()派生的所有类似MAX值

时间:2014-02-19 12:48:35

标签: mysql sql database

我有一个简单的MySQL表看起来:

    Table: Citizen

    Name    Country
    ----    ------
    Adam    USA
    Eva     Russia
    Arman   India
    Peter   USA
    Martin  Russia
    Jack    Finland
    Juno    Russia
    Fox     USA
    Maya    Finland

这样的简单查询
SELECT Country, COUNT(Name) People FROM Citizen  GROUP BY Country

会给我

Country     People
-------     ------
USA         3
Russia      3
Finland     2
India       1

我想找到人数最多的国家/地区。在平局的情况下(即两个国家的最大人数相同),列出所有这样的国家。结果表应如下所示

Country     MaxPeople
-------     ------
USA         3
Russia      3

我学习了一些关于派生表的知识并提出了这个问题:

SELECT Country, MAX(TotCit) 
FROM (SELECT Country, COUNT(People) TotCit 
      FROM Citizen GROUP BY Country) 
AS CitTable

结果是

Country   Max(TotCit)
-------   -----------
Finland   3

任何可能的解决方案?

2 个答案:

答案 0 :(得分:3)

如果您需要所有国家/地区,那么查询有点麻烦:

SELECT Country, COUNT(Name) as People
FROM Citizen 
GROUP BY Country
HAVING COUNT(Name) = (select max(cnt)
                      from (select COUNT(Name) as cnt
                            from Citizen
                            group by Country
                           ) c
                     );

查询可以满足您的需求。 HAVING子句首先计算每个国家/地区的计数,然后计算max()并将其与汇总值进行比较。

顺便说一下,这在大多数其他数据库中要容易得多,因为它们支持窗口/分析功能。

答案 1 :(得分:0)

戈登的询问,简化了一下。

  • 除非COUNT(Name)是可以为空的列,否则您不需要Nname
  • 可以使用LIMIT的简单子查询替换2嵌套子查询:

    SELECT Country, COUNT(*) AS People
    FROM Citizen 
    GROUP BY Country
    HAVING COUNT(*) = 
           ( SELECT COUNT(*) AS People
             FROM Citizen
             GROUP BY Country
             ORDER BY People DESC
             LIMIT 1
           ) ;
    

HAVING中的条件可能会导致查询效率非常低,因此您可以重写为:

SELECT 
    g.Country, g.People
FROM
  ( SELECT COUNT(*) AS People
    FROM Citizen
    GROUP BY Country
    ORDER BY cnt DESC
    LIMIT 1
  ) AS m
  JOIN
  ( SELECT Country, COUNT(*) AS People
    FROM Citizen  
    GROUP BY Country
  ) AS g
      ON g.People = m.People ;