小编典典

SQL-SUM()的条件

sql

是否可以做这样的事情:

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


阅读 182

收藏
2021-03-10

共1个答案

小编典典

这可以通过HAVING子句完成:

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语句的位置

查询优化器也不应该多次计算平均值,因此在这里不必担心。

正如@jagra的答案中提到的那样,您应该可以使用AVG()而不是SUM() / COUNT()

2021-03-10