公用表表达示展BOM示例,并计算累计用量。
示例数据库为SQL示例数据库AdventureWorks,表名 Production.BillOfMaterials,Production.Product
;with bom as ( select b.ProductAssemblyID,b.ComponentID,b.BOMLevel,b.PerAssemblyQty,cast(b.PerAssemblyQty as decimal(10,6)) qty,ROW_NUMBER() over(order by getdate()) od from Production.BillOfMaterials b where b.ComponentID=767 union all select b.ProductAssemblyID,b.ComponentID,b.BOMLevel,b.PerAssemblyQty,cast(b.PerAssemblyQty*bom.qty as decimal(10,6)) ,ROW_NUMBER() over(order by getdate())+ bom.od*100 from Production.BillOfMaterials b join bom on b.ProductAssemblyID=bom.ComponentID ) select p.ProductNumber '物料编码',replicate('..',bom.bomlevel)+ p.Name '物料名称' ,bom.BOMLevel '层级',bom.PerAssemblyQty 'BOM用量', bom.qty '累计用量',bom.od '排序' from bom join Production.Product p on bom.ComponentID=p.ProductID order by rtrim(od)