Recursive CTE Bill of Materials Explosion
Explode product bills of materials with a recursive CTE, multiplying quantities down each assembly path and rolling up costs.
Code
-- BOM 展开:每层用量沿路径连乘
WITH RECURSIVE explosion AS (
SELECT
b.child_part_id,
b.parent_part_id,
b.quantity_per,
b.quantity_per AS total_quantity,
b.child_part_id::text AS path,
1 AS level
FROM bom_edges b
WHERE b.parent_part_id = 'BIKE-100' -- 顶层成品
UNION ALL
SELECT
c.child_part_id,
c.parent_part_id,
c.quantity_per,
e.total_quantity * c.quantity_per,
e.path || ' > ' || c.child_part_id,
e.level + 1
FROM bom_edges c
JOIN explosion e ON c.parent_part_id = e.child_part_id
WHERE e.level < 10 -- 深度保险丝
)
SELECT
child_part_id,
level,
total_quantity,
path
FROM explosion
ORDER BY path;
-- 成本汇总:叶子节件数乘单价回卷到成品
WITH costs AS (
SELECT
child_part_id,
SUM(total_quantity) AS qty_needed
FROM explosion
GROUP BY child_part_id
)
SELECT
c.child_part_id,
c.qty_needed,
p.unit_cost_cents,
c.qty_needed * p.unit_cost_cents AS extended_cost
FROM costs c
JOIN parts p ON p.part_id = c.child_part_id
ORDER BY extended_cost DESC;How the snippet works
The file runs SELECT statements, touching bom_edges, explosion, costs and parts.
The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause deciding which rows the statement applies to; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION pulling result sets from separate queries into one result.
Points of care
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Applying it
Point it at the bom_edges table.
Statements that matter
WITH costs AS (
SELECT
child_part_id,
SUM(total_quantity) AS qty_needed
FROM explosion
GROUP BY child_part_id
)
SELECT
c.child_part_id,
c.qty_needed,
p.unit_cost_cents,
c.qty_needed * p.unit_cost_cents AS extended_cost
FROM costs c
JOIN parts p ON p.part_id = c.child_part_id
ORDER BY extended_cost DESC;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `bom_edges`, `explosion`, `costs`, `parts`, combined through 2 joins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.