SQL - WHERE Condition on SUM()

前端 未结 4 459
长发绾君心
长发绾君心 2020-12-19 18:12

Is it possible to do something like this:

SELECT 
  `e`.*, 
  `rt`.`review_id`, 
  (SUM(vt.percent) / COUNT(vt.percent)) AS rating 
FROM `catalog_product_ent         


        
4条回答
  •  独厮守ぢ
    2020-12-19 18:47

    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
    

    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.

    As was mentioned in @jagra's answer, you should be able to use AVG() instead of SUM() / COUNT()

提交回复
热议问题