SQL - WHERE Condition on SUM()(SQL - SUM() 上的 WHERE 条件)
问题描述
是否可以这样做:
SELECT
`e`.*,
`rt`.`review_id`,
(SUM(vt.percent) / COUNT(vt.percent)) AS rating
FROM `catalog_product_entity` AS `e`
INNER JOIN `rating_option_vote` AS `vt`
ON vt.review_id = e.review_id
WHERE (rating >= '0')
GROUP BY `vt`.`review_id`
我特别想在除法结果值上加上 where 条件
In particular I would like to put a where condition on the division result value
推荐答案
这可以通过 HAVING 子句来完成:
This can be accomplished with a HAVING clause:
SELECT e.*, rt.review_id, (SUM(vt.percent) / COUNT(vt.percent)) AS rating
FROM catalog_product_entity AS e
INNER JOIN rating_option_vote AS vt ON e.review_id = vt.review_id
GROUP BY vt.review_id
HAVING (SUM(vt.percent) / COUNT(vt.percent)) >= 0
ORDER BY (SUM(vt.percent) / COUNT(vt.percent)) ASC
注意:添加了 ORDER BY 语句的放置位置
Note: Added where to put ORDER BY statement
查询优化器也不应该多次计算平均值,所以这里不应该担心.
The query optimizer should also not calculate the Average multiple times either, so that should not be a concern here.
正如@jagra 的回答中提到的,您应该能够使用 AVG() 而不是 SUM()/COUNT()
As was mentioned in @jagra's answer, you should be able to use AVG() instead of SUM() / COUNT()
这篇关于SQL - SUM() 上的 WHERE 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL - SUM() 上的 WHERE 条件
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
