Compare album totals with the average sold album
Your task
Return title and copies_sold for sold albums with a total strictly above the average copies sold per sold album. Sort by title.
First summarize each sold album once so sales with more rows cannot skew the average.
Sample data
| id | title | genre | price | stock |
|---|---|---|---|---|
| 1 | Night Bus | Jazz | 18 | 7 |
| 2 | Static Bloom | Indie | 22 | 4 |
| 3 | Soft Circuit | Electronic | 24 | 0 |
| 4 | Blue Hour | Jazz | 16 | 3 |
| 5 | Coastline | Indie | 19 | 8 |
| 6 | Low Tide | Ambient | 21 | 2 |
Expected output
| title | copies_sold |
|---|---|
| Night Bus | 5 |
| Static Bloom | 3 |
Show a hint
Use one CTE for copies per sold album and compare each total with AVG over that CTE.
Subqueries and CTEs guide
Use a query as a value
An aggregate without GROUP BY produces one row. A single-column subquery can therefore provide a scalar value for a comparison. Here each price is compared with an average calculated across the whole table.
SELECT title, price
FROM albums
WHERE price < (SELECT AVG(price) FROM albums);Ask whether a related row exists
An EXISTS subquery only needs to produce one row to be true. It refers to a.id from the outer query, so the test is evaluated for the current album. The expression in the inner SELECT is immaterial to the existence test.
SELECT a.title
FROM albums AS a
WHERE EXISTS (
SELECT 1
FROM sales AS s
WHERE s.album_id = a.id AND s.quantity > 1
);Name intermediate results with WITH
A common table expression gives an intermediate query a name for a single statement. Here the CTE summarizes sales before joining them to albums. Read the CTE on its own first, then read the final SELECT to see how the summary is used.
WITH totals AS (
SELECT album_id, SUM(quantity) AS copies
FROM sales
GROUP BY album_id
)
SELECT a.title, COALESCE(t.copies, 0) AS copies
FROM albums AS a
LEFT JOIN totals AS t ON t.album_id = a.id;Worked solution
WITH totals AS (SELECT album_id, SUM(quantity) AS copies_sold FROM sales GROUP BY album_id) SELECT a.title,t.copies_sold FROM totals t JOIN albums a ON a.id=t.album_id WHERE t.copies_sold > (SELECT AVG(copies_sold) FROM totals) ORDER BY a.title;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
