【问题标题】:GROUP BY with Count > Certain_NumberGROUP BY with Count > certain_Number
【发布时间】:2020-08-02 18:25:46
【问题描述】:

我的桌子:

City   |   Country
--------------------
City1  |   Country1
City2  |   Country1
City3  |   Country1
City4  |   Country1
City1  |   Country2
City2  |   Country2

我想选择那些城市少于 3 个的国家:

Count   |   Country
--------------------
2       |   Country2

所以,我的查询是:

SELECT Country, COUNT(*) AS Count FROM Table GROUP BY Country WHERE Table.Count < 3

不工作。

【问题讨论】:

    标签: mysql sql group-by count where-clause


    【解决方案1】:

    您不能在where 子句中使用聚合表达式(此子句在聚合实际发生之前处理)。相反,您可以使用having 子句:

    SELECT country, COUNT(*) AS Count 
    FROM Table 
    GROUP BY country 
    HAVING COUNT(*) < 3
    

    【讨论】:

      【解决方案2】:

      由于 Count 不是表中的列,因此您不能定义为 Table.Count,而是可以提供别名。 WHERE 子句对列应用条件。 HAVING子句对聚合函数应用条件,只能在group by后使用

      SELECT Country, COUNT(*) AS Count FROM Table GROUP BY Country HAVING Count < 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-30
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        相关资源
        最近更新 更多