如何避免错误“WHERE中不允许聚合函数”

时间:2014-01-08 09:34:20

标签: mysql sql aggregate-functions

此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;

如何避免此错误?

3 个答案:

答案 0 :(得分:71)

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时)

答案 1 :(得分:5)

使用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

答案 2 :(得分:0)

如果我们有条件列出的价格大于订单表中列出的价格中位数,那么自我加入是否会加入折扣?

EG。 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