← All SQL interview questions

Raw materials needed to build one finished product

HardRecursive CTEsWalmartTargetAmazon

A manufacturing planner stores a bill of materials in bom: each row says that one unit of parent_item needs qty_per_parent units of child_item. Sub-assemblies are themselves built from other items, to any depth, and the same raw part can appear in several branches.

For the finished product Smart Speaker, return every raw component (an item that is never a parent of anything) with the total_qty needed to build one speaker. Quantities multiply down the tree and must be added up across branches. Order by component.

Sample data

Table: bom

18 row(s) · showing first 8

parent_itemTEXTchild_itemTEXTqty_per_parentINT
Smart SpeakerMainboard1
Smart SpeakerSpeaker Driver2
Smart SpeakerEnclosure1
Smart SpeakerPower Cable1
MainboardChipset1
MainboardCapacitor12
MainboardPCB1
Speaker DriverMagnet1