We have a large data table that was being used to return total average price, however this and other queries were taking so long to process that we have aggragated the results by country and day.
This is an example of the original table:
Country | code | Price | Date
--------------------------------------
IND | XXZ | 7.435 | 2021-01-01
IND | XSZ | 7.445 | 2021-01-01
IND | XAZ | 6.435 | 2021-01-01
USA | XYN | 2.524 | 2021-01-02
USA | AYD | 9.524 | 2021-01-02
USA | XYD | 2.534 | 2021-01-02
AUS | YYB | 1.819 | 2021-01-03
AUS | YSB | 4.319 | 2021-01-03
--------------------------------------
AVG(Price) = 5.254375
SELECT AVG(Price) from table
Results in 5.254375
To optimise all queries against this recordset, we aggregate the table using this expression:
SELECT country,sum(price),Avg(price),date
FROM table
GROUP BY country,date
Country | sum(Price)| AVG(Price) | Date
----------------------------------------------
IND | 21.315 | 7.105 | 2021-01-01
USA | 14.582 | 4.86066667 | 2021-01-02
AUS | 1.638 | 3.069 | 2021-01-03
-----------------------------------------------
Avg = 5.011555557
When I take the
Avg(Avg(Price)) = 5.011555557, this value doesn't match with the AVG(Price) = 5.254375 on non-aggregated data.
However now in the report, we still want to be able to show the correct average figure, but we cannot use the original table because thee query takes too long to process.
How can we calculate the overall average price, only using this aggregated record set?