MySQL中的加权平均值计算?

时间:2010-10-08 01:17:45

标签: database mysql query-optimization

我目前正在使用以下查询来获取一些数字:

SELECT gid, count(gid), (SELECT cou FROM size WHERE gid = infor.gid)       
FROM infor 
WHERE id==4325 
GROUP BY gid;

我目前阶段的输出如下:

+----------+-----------------+---------------------------------------------------------------+
| gid      | count(gid)      | (SELECT gid FROM size WHERE gid=infor.gid)                    |
+----------+-----------------+---------------------------------------------------------------+
|       19 |               1 |                                                            19 | 
|       27 |               4 |                                                            27 | 
|      556 |               1 |                                                           556 | 
+----------+-----------------+---------------------------------------------------------------+

我试图计算加权平均值,即

  

(1 * 19 + 4 * 27 + 1 * 556)/(19 + 27 + 556)

有没有办法使用单个查询执行此操作?

2 个答案:

答案 0 :(得分:14)

使用:

SELECT SUM(x.num * x.gid) / SUM(x.cou)
  FROM (SELECT i.gid,
               COUNT(i.gid) AS num,
               s.cou
          FROM infor i
     LEFT JOIN SIZE s ON s.gid = i.gid
         WHERE i.id = 4325
      GROUP BY i.gid) x

答案 1 :(得分:1)

您可以将原始查询作为子查询放置并对记录进行SUM整理。我无法测试这个,因为我没有你做的数据集,但它应该在理论上工作;)

SELECT SUM(gid)/SUM(weights) AS calculated_average FROM (
  SELECT gid, (COUNT(gid) * gid) AS weights
  FROM infor 
  WHERE id = 4325 
  GROUP BY gid);