SQL - WHERE条件SUM()

时间:2013-03-26 17:45:36

标签: mysql sql sum conditional-statements

是否可以做这样的事情:

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

4 个答案:

答案 0 :(得分:4)

这可以通过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()

答案 1 :(得分:2)

您可以使用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 vt.review_id = e.review_id 
GROUP BY `vt`.`review_id` 
HAVING rating >= 0;

正如您的问题被标记为MySQL,此解决方案应该可以正常工作,如文档所示:

...在标准SQL中,包含GROUP BY子句的查询不能引用HAVING子句中未在GROUP BY子句中命名的非聚合列。 MySQL扩展允许引用此类列以简化计算。 ......

默认情况下,在官方MySQL编译中启用此扩展。

参考:http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html(页面上第一次出现HAVING字样)

答案 2 :(得分:1)

在使用聚合函数进行过滤时,您需要使用HAVING子句:

SELECT 
  # `e`.*, => is this needed
  `rt`.`review_id`, 
  (SUM(vt.percent) / COUNT(vt.percent)) AS rating 
  AVG(vt.percent) AS rating1 # same as above 
FROM `catalog_product_entity` AS `e` 
INNER JOIN `rating_option_vote` AS `vt`
  ON vt.review_id = e.review_id 
GROUP BY `vt`.`review_id`
HAVING AVG(vt.percent) > 0

另外两个注释:

1)SUM(x)/ COUNT(x)< => AVG(x)的

2)您在选择中包括e。*但不包括在组中。 MySql允许你这样做,但其他数据库不会。

答案 3 :(得分:0)

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 vt.review_id = e.review_id 
WHERE ( rating >= '0') 
GROUP BY `vt`.`review_id'
HAVING (SUM(vt.percent) / COUNT(vt.percent)) > 0