MySQL - 在WHERE中查找平均数

时间:2011-01-03 07:56:00

标签: mysql

我试图根据WHERE子句找到某些行的总和的平均数。这是我到目前为止所做的:

SELECT SUM(rating), id
FROM rating
WHERE id=$id;");

所以类似“行数之和”/“返回的行数”

3 个答案:

答案 0 :(得分:4)

AVG(expr):返回expr的平均值,例如

SELECT
    AVG(rating),
    id
FROM
    rating
WHERE
    id=$id
GROUP BY
    id

(编辑:忘记GROUP BY

答案 1 :(得分:0)

不是那么简单:

SELECT SUM(rating) AS sum, AVG(rating) AS avg, id
  FROM rating
 WHERE id = $id
 GROUP BY id;

答案 2 :(得分:0)

MySQL实际上有一个内置的平均功能

SELECT AVG(rating) as average_rating,
id
FROM rating
WHERE id=$id
GROUP BY id

如果由于某种原因你真的想使用SUM,你可以使用

SELECT SUM(rating)/COUNT(rating) as average_rating,
id
FROM rating
WHERE id=$id
GROUP BY id

希望不是!