← Back to SQL, page 25

sql-0492 · Medium mid

A dashboard shows each product's 'average rating' as the average of the per-store averages, and it differs from the true average. Find the cause.

Averaging averages gives every group the same weight regardless of how many rows it holds, so a store with two reviews counts as much as a store with two hundred. Compute the overall average from the underlying rows, or as SUM(total) / SUM(count) from the group totals.

Full answer
sql
CREATE TABLE reviews (product TEXT, store TEXT, rating INTEGER);
INSERT INTO reviews VALUES
 ('Lamp','North',5),('Lamp','North',5),
 ('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3);

The query as written:

sql
SELECT product, AVG(store_avg) AS avg_of_averages FROM (
  SELECT product, store, AVG(rating) AS store_avg FROM reviews GROUP BY product, store
) GROUP BY product;
productavg_of_averages
Lamp3.75

The North store has two perfect ratings and South has six lukewarm ones. Averaging the two store averages (5.0 and 2.5) gives 3.75, as if each store had the same number of reviews.

A corrected version:

sql
SELECT product, AVG(rating) AS true_avg, SUM(rating) * 1.0 / COUNT(*) AS same_thing_from_totals FROM reviews GROUP BY product;
producttrue_avgsame_thing_from_totals
Lamp3.1253.125

The real average over all eight reviews is 3.125, and the total-over-count form agrees. A weighted average is the correct way to roll up group averages, which is why stored summaries should keep sums and counts, not just averages. Multiplying by 1.0 avoids integer division in SQLite.

sql
CREATE TABLE reviews (product TEXT, store TEXT, rating INTEGER);
INSERT INTO reviews VALUES
 ('Lamp','North',5),('Lamp','North',5),
 ('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3);

SELECT product, AVG(store_avg) AS avg_of_averages FROM (
  SELECT product, store, AVG(rating) AS store_avg FROM reviews GROUP BY product, store
) GROUP BY product;

SELECT product, AVG(rating) AS true_avg, SUM(rating) * 1.0 / COUNT(*) AS same_thing_from_totals FROM reviews GROUP BY product;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Average of averages ignores group sizes
  • Compute from rows or from sum and count
  • Store sum and count in summaries
  • Beware integer division

Common mistakes

  • Rolling up pre-averaged numbers
  • Keeping only averages in summary tables

Follow-ups

  • How would you merge two stored (sum, count) summaries?
  • When is an unweighted average of groups actually wanted?

Tips

  • Use extreme group sizes in the example