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 条件


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01