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;| product | avg_of_averages |
|---|---|
| Lamp | 3.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;| product | true_avg | same_thing_from_totals |
|---|---|---|
| Lamp | 3.125 | 3.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