Full answer
sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
need(part, qty) AS (
SELECT 'bike', 1
UNION ALL
SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;| part | total |
|---|---|
| bolt | 8 |
| frame | 1 |
| hub | 2 |
| spoke | 64 |
| wheel | 2 |
The recursion carries the cumulative quantity down the tree: 1 bike, 2 wheels, 2 × 32 = 64 spokes, 2 × 1 = 2 hubs. The frame's 4 bolts and the wheels' bolts (2 × 2 = 4) are added together in the final GROUP BY, giving 8.
Without the final SUM, a part that appears in several branches shows up as several rows. The same pattern answers "total cost of a product" if each leaf carries a unit price: multiply the quantity by the price and sum.
sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
need(part, qty) AS (
SELECT 'bike', 1
UNION ALL
SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Seed the recursion with the top item and quantity 1
- Multiply quantities along each path
- Sum per part at the end
- The same part can appear in several branches
Common mistakes
- Adding quantities instead of multiplying them
- Forgetting the final aggregation
Follow-ups
- How would you compute the cost of one bike?
- How would you detect a cycle in the parts data?
Tips
- Walk through the multiplication for spokes