【问题标题】:How to avoid error "aggregate functions are not allowed in WHERE"如何避免错误“WHERE 中不允许使用聚合函数”
【发布时间】:2014-01-26 07:43:46
【问题描述】:

这个sql代码抛出一个

WHERE 中不允许使用聚合函数

SELECT o.ID ,  count(p.CAT)
FROM Orders o
INNER JOIN Products p ON o.P_ID = p.P_ID 
WHERE count(p.CAT) > 3
GROUP BY o.ID;

我怎样才能避免这个错误?

【问题讨论】:

    标签: mysql sql aggregate-functions


    【解决方案1】:

    WHERE 子句替换为HAVING,如下所示:

    SELECT o.ID ,  count(p.CAT)
    FROM Orders o
    INNER JOIN Products p ON o.P_ID = p.P_ID 
    GROUP BY o.ID
    HAVING count(p.CAT) > 3;
    

    HAVINGWHERE 类似,都用于过滤结果记录,但HAVING 用于过滤聚合数据(使用GROUP BY 时)。

    【讨论】:

      【解决方案2】:

      使用HAVING 子句代替WHERE

      试试这个:

      SELECT o.ID, COUNT(p.CAT) cnt
      FROM Orders o
      INNER JOIN Products p ON o.P_ID = p.P_ID 
      GROUP BY o.ID HAVING cnt > 3
      

      【讨论】:

        【解决方案3】:

        如果我们有条件列出高于订单表中所列价格中位数的价格,self join 是否会与 join 折腾?

        例如。 order_item, Order_Price

        因为聚合函数不能在 WHERE 子句中使用 >

        select a.order_item_product_price, count(distinct 
        a.order_item_product_price) from 
        default.order_items a , default.order_items b
        where a.order_item_product_price = b.order_item_product_price
        group by a.order_item_product_price
        having a.order_item_product_price > appx_median(b.order_item_product_price)
        order by a.order_item_product_price limit 10
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-16
          • 2019-02-21
          • 1970-01-01
          • 2017-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多