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?
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With