开发者

Weighted average calculation in MySQL?

I am currently using the following query to get some numbers:

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

The output I am getting at my current stage is the following:

+----------+-----------------+---------------------------------------------------------------+
| gid      | count(gid)      | (SELECT gid FROM size WHERE gid=infor.gid)                    |
+----------+-----------------+---------------------------------------------------------------+
|       19 |               1 |                                      开发者_JS百科                      19 | 
|       27 |               4 |                                                            27 | 
|      556 |               1 |                                                           556 | 
+----------+-----------------+---------------------------------------------------------------+

I am trying to calculate the weighted average i.e.

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

Is there a way to do this using a single query?


Use:

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


You could place your original query as a sub-query and SUM the records. I could not test this as I don't have the dataset you do, but it should work in theory ;)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜