bom表(产品,零件,用量)
数据:
--------------------------------------------
产品 零件 用量
--------------------------------------------
a a1 1
a1 a11 1
a11 a111 1
a a2 1
a2 a22 1
a22 a222 1
b b1 1
b1 b11 1
b b2 1
b2 b22 1
b22 b222 1
请问如何列出产品所用零件的零件bom阶次清单
例:
--------------------------------------------
阶次 产品 零件 用量
--------------------------------------------
0 a
.1 a1 1
..2 a11 1
...3 a111 1
.1 a2 1
..2 a22 1
...3 a222 1
谢谢!
------最佳解决方案--------------------
USE test
GO
-->生成表bom
--if object_id('bom') is not null
-- drop table bom
--Go
--Create table bom([产品] nvarchar(3),[零件] nvarchar(4),[用量] smallint)
--Insert into bom
--Select N'a',N'a1',1
--Union all Select N'a1',N'a11',1
--Union all Select N'a11',N'a111',1
--Union all Select N'a',N'a2',1
--Union all Select N'a2',N'a22',1
--Union all Select N'a22',N'a222',1
--Union all Select N'b',N'b1',1
--Union all Select N'b1',N'b11',1
--Union all Select N'b',N'b2',1
--Union all Select N'b2',N'b22',1
--Union all Select N'b22',N'b222',1
;WITH Result AS (
SELECT
1 AS LEVEL
,ROW_NUMBER()OVER(PARTITION BY 产品 ORDER BY 零件) AS Row
,*
FROM bom AS a
WHERE NOT EXISTS(SELECT 1 FROM bom AS x WHERE x.零件=a.产品)
UNION ALL
SELECT
b.Level+1
,b.Row
,b.产品
,a.零件
,a.用量
FROM bom AS a
INNER JOIN Result AS b ON a.产品=b.零件
)
SELECT
阶次
,CASE WHEN Level>0 THEN '' ELSE 产品 END AS 产品
,零件
,用量
FROM (
SELECT DISTINCT
'0' AS 阶次
,产品
,'' AS 零件
,用量
,0 AS LEVEL
,1 AS Row
FROM bom AS a
WHERE NOT EXISTS(SELECT 1 FROM bom AS x WHERE x.零件=a.产品)
UNION ALL
SELECT
REPLICATE('.',Level)+LTRIM(Level)
,产品
,零件
,用量