开发者

SQL with condition on calculated value

开发者 https://www.devze.com 2023-02-11 01:35 出处:网络
I have a table with products, their amount and their price. I need to select all entries where the average price per article is between a开发者_如何学C range.

I have a table with products, their amount and their price. I need to select all entries where the average price per article is between a开发者_如何学C range. My query so far:

SELECT productid,AVG(SUM(price)/SUM(amount)) AS avg 
FROM stock WHERE avg>=$from AND avg<=$to GROUP BY productid

If do this, it tells me avg doesn't exist. Also I obviously need to group by because the sum and average need to be per wine


You need to put it in the HAVING clause. You cannot filter by the result of aggregates using WHERE.

MySQL does allow you to reference column aliases in HAVING. You might need

SELECT 
      productid,
      AVG(price/amount) AS avg ,
      /*SUM(price)/SUM(amount) AS avg (<--- Or perhaps this?)*/
FROM stock 
GROUP BY productid
HAVING avg>=$from AND avg<=$to 

But I'm not sure exactly what you are trying to do with AVG(SUM(price)/SUM(amount)) can you show some example data?

0

精彩评论

暂无评论...
验证码 换一张
取 消