Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 |                                                            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?

like image 258
Legend Avatar asked Oct 08 '10 01:10

Legend


People also ask

What is weighted average in SQL?

Calculating Weighted Moving Average in SQL A weighted moving average is a moving average where the previous values within the sliding widnow are given different weights.

How is average calculated in MySQL?

You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values. For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operator will return 2 i.e., (1 + 2 + 3) / 3 .


2 Answers

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
like image 199
OMG Ponies Avatar answered Oct 27 '22 08:10

OMG Ponies


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);
like image 41
Jason McCreary Avatar answered Oct 27 '22 09:10

Jason McCreary