Compare inventory value and historical sales by genre
Your task
For every genre, return genre, inventory_value as price times current stock summed across albums, and listed_sales_value as listed price times copies sold. Include genres with no sales and sort by genre.
Inventory value belongs to the album row. Summarize its sales before joining so inventory never gets counted once per transaction.
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
| genre | inventory_value | listed_sales_value |
|---|---|---|
| Ambient | 42 | 0 |
| Electronic | 0 | 0 |
| Indie | 240 | 85 |
| Jazz | 174 | 122 |
Show a hint
Aggregate quantity once per album, then join to the album rows and sum each metric by genre.
Optimization and capstones guide
Compare equivalent filters
A function on an indexed column can hide the key from a direct range lookup. The two predicates here select the same January dates in this dataset. Compare the plans and look for a constrained SEARCH on the second query.
EXPLAIN QUERY PLAN
SELECT id FROM receipts WHERE STRFTIME('%Y-%m', sold_on) = '2025-01';
EXPLAIN QUERY PLAN
SELECT id FROM receipts
WHERE sold_on >= '2025-01-01' AND sold_on < '2025-02-01';Continue from a stable key
OFFSET skips entries before the requested page. With keyset pagination, use the last ID from the previous page as a boundary. The order and boundary must use the same key. Use a unique tie-breaker if the leading sort column can repeat.
EXPLAIN QUERY PLAN
SELECT id, title FROM catalog
WHERE id > 500
ORDER BY id
LIMIT 5;Summarize first, compare second
Start reports by deciding what one result row represents. This report groups receipts by month, then compares monthly totals with LAG. If February has no receipts, the next row compares with January. Generate a calendar CTE and left join it when gaps need to appear explicitly.
WITH monthly AS (
SELECT STRFTIME('%Y-%m', sold_on) AS month, SUM(amount) AS total
FROM receipts
GROUP BY month
)
SELECT month, total, total - LAG(total) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;Worked solution
WITH sold AS (SELECT album_id,SUM(quantity) AS copies FROM sales GROUP BY album_id) SELECT a.genre,SUM(a.price*a.stock) AS inventory_value,SUM(a.price*COALESCE(s.copies,0)) AS listed_sales_value FROM albums a LEFT JOIN sold s ON s.album_id=a.id GROUP BY a.genre ORDER BY a.genre;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
