Walk a bill of materials
Quantities multiply down the tree; a final GROUP BY sums duplicate parts.
The task
Assembly 100 contains sub-assemblies that contain parts. You need the flattened shopping list: every component below the assembly and the total quantity it takes to build one.
The snippet
Written for PostgreSQL. Versions for SQL Server and Oracle are under Variations.
WITH RECURSIVE breakdown AS (
SELECT pc.child_id AS part_id, pc.quantity, 1 AS level
FROM part_children pc
WHERE pc.part_id = 100
UNION ALL
SELECT pc.child_id, pc.quantity * b.quantity, b.level + 1
FROM part_children pc
JOIN breakdown b ON pc.part_id = b.part_id
)
SELECT p.name, SUM(b.quantity) AS total_quantity, MIN(b.level) AS first_used_at_level
FROM breakdown b
JOIN parts p ON p.id = b.part_id
GROUP BY p.name
ORDER BY p.name;
Fonctionnement
Each recursive round multiplies the child's own quantity by the quantity accumulated so far, so a screw needed 4 per bracket and 3 brackets per assembly becomes 12. The final GROUP BY merges parts that appear in several sub-assemblies into one total. The list includes the sub-assemblies themselves; add WHERE NOT EXISTS (SELECT 1 FROM part_children x WHERE x.part_id = b.part_id) to keep only leaf parts. Runs as-is on PostgreSQL, MySQL 8 and SQLite; a parts loop means bad data and needs the same guard as any recursive CTE.
Variations
Indented tree listing (PostgreSQL)
PostgreSQLWITH RECURSIVE tree AS (
SELECT p.id, p.name, 0 AS level,
CAST(p.name AS text) AS path
FROM parts p
WHERE p.id = 100
UNION ALL
SELECT pc.child_id, p2.name, t.level + 1,
t.path || ' > ' || p2.name
FROM part_children pc
JOIN tree t ON pc.part_id = t.id
JOIN parts p2 ON p2.id = pc.child_id
)
SELECT REPEAT(' ', level) || name AS indented, path
FROM tree
ORDER BY path;
SQL Server and Oracle: column list, no RECURSIVE
SQL Server OracleWITH breakdown (part_id, quantity, lvl) AS (
SELECT pc.child_id, pc.quantity, 1
FROM part_children pc
WHERE pc.part_id = 100
UNION ALL
SELECT pc.child_id, pc.quantity * b.quantity, b.lvl + 1
FROM part_children pc
JOIN breakdown b ON pc.part_id = b.part_id
)
SELECT p.name, SUM(b.quantity) AS total_quantity, MIN(b.lvl) AS first_used_at_level
FROM breakdown b
JOIN parts p ON p.id = b.part_id
GROUP BY p.name
ORDER BY p.name;
Questions that come up
Why multiply quantities instead of summing them?
Because a child's requirement is per one unit of its parent. The parent needs 3 brackets, and each bracket needs 4 screws, so the assembly needs 3 x 4 screws. Multiplying down each edge gives the true per-assembly requirement.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.