带有计算值条件的 SQL
我有一张桌子,上面有产品、数量和价格。我需要选择每篇文章的平均价格在一定范围内的所有条目。 到目前为止我的查询:
SELECT productid,AVG(SUM(price)/SUM(amount)) AS avg
FROM stock WHERE avg>=$from AND avg<=$to GROUP BY productid
如果这样做,它告诉我 avg 不存在。 另外,我显然需要分组,因为总和和平均值需要针对每种葡萄酒
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将其放在
HAVING
子句中。您无法使用WHERE
按聚合结果进行过滤。MySQL 允许您在
HAVING
中引用列别名。您可能需要但我不确定您到底想用
AVG(SUM(price)/SUM(amount))
做什么,您可以显示一些示例数据吗?You need to put it in the
HAVING
clause. You cannot filter by the result of aggregates usingWHERE
.MySQL does allow you to reference column aliases in
HAVING
. You might needBut I'm not sure exactly what you are trying to do with
AVG(SUM(price)/SUM(amount))
can you show some example data?