Sql 材料工程量清单
我想列出材料清单的总额。我制作了一些示例代码: 正如您所看到的,由于递归级别,物料清单正在重复 所以,我希望结果是:Sql 材料工程量清单,sql,sql-server-2008,Sql,Sql Server 2008,我想列出材料清单的总额。我制作了一些示例代码: 正如您所看到的,由于递归级别,物料清单正在重复 所以,我希望结果是: ┌────────────┬───────────┬────────────┐ │家长党│儿童党│子零件数量│ ├────────────┼───────────┼────────────┤ │淋浴-A│玻璃-A│2.│ ├────────────┼───────────┼────────────┤ │玻璃-A│某样东西│10│ ├────────────┼─────────
┌────────────┬───────────┬────────────┐
│家长党│儿童党│子零件数量│
├────────────┼───────────┼────────────┤
│淋浴-A│玻璃-A│2.│
├────────────┼───────────┼────────────┤
│玻璃-A│某样东西│10│
├────────────┼───────────┼────────────┤
│某样东西│某物-B│30│
└────────────┴───────────┴────────────┘代码>
我正在考虑按最高递归级别分组,但感觉很混乱。是一个可能有用的解决方案:
; with cte_gettopparents as
(
select a.*, ROW_NUMBER() over (order by a.ParentPartId) as ordr
from BillOfMaterial a
where not exists
(
select 1
from BillOfMaterial b
where b.ChildPartId = a.ParentPartId
)
)
--select * from cte_gettopparents
,
cte_getallchildren as
(
select *
from cte_gettopparents
union all
select a.ParentPartId, a.ChildPartId ,a.ChildPartQty * b.ChildPartQty,b.ordr
from BillOfMaterial a join cte_getallchildren b
on b.ChildPartId = a.ParentPartId
)
select ParentPartId, ChildPartId ,ChildPartQty, ordr as [hierarchyid]
from cte_getallchildren
order by ordr,ChildPartId
如果希望得到不同的结果,请使用:
select Distinct ParentPartId, ChildPartId ,ChildPartQty
from cte_getallchildren
order by ChildPartQty