我目前正在使用以下查询来获取一些数字:
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)
有没有办法使用单个查询?
解决方法
使用:
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