此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;
如何避免此错误?
答案 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;
HAVING
与WHERE
类似,它们都用于过滤生成的记录,但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