我编写了SQL代码以完全爆炸所有物料清单:
这是表格数据:
CREATE TABLE bomline(
itemno VARCHAR(6) NOT NULL
,compno VARCHAR(6) NOT NULL
,quantity NUMERIC(9,6) NOT NULL
,PRIMARY KEY(itemno,compno)
);
INSERT INTO bomline(itemno,compno,quantity) VALUES ('1000','1100',2.000000);
INSERT INTO bomline(itemno,compno,quantity) VALUES ('1100','1200',3.000000);
INSERT INTO bomline(itemno,compno,quantity) VALUES ('2000','2100',4.000000);
INSERT INTO bomline(itemno,compno,quantity) VALUES ('2100','2200',2.000000);
这是我的SQL代码:
WITH tmpbom([itemno], [compno], [quantity], [level])
AS (SELECT S1.[itemno],
S1.[compno],
CAST(S1.[quantity] AS NUMERIC),
1
FROM bomline AS S1
UNION ALL
SELECT S2.[itemno],
S2.[compno],
CAST(S2.[quantity] * TS.[quantity] AS NUMERIC),
TS.[level] + 1
FROM bomline AS S2
INNER JOIN tmpbom AS TS
ON S2.[itemno] = TS.[compno])
SELECT [itemno],
[compno],
Isnull(quantity, 0) AS [quantity]
FROM tmpbom
这就是我现在所得到的:
+--------+---------+-----------+
| ItemNo | CompNo | Quantity |
+--------+---------+-----------+
| 1000 | 1100 | 2.000000 |
| 1100 | 1200 | 3.000000 |
| 2000 | 2100 | 4.000000 |
| 2100 | 2200 | 2.000000 |
| 2100 | 2200 | 8.000000 |
| 1100 | 1200 | 6.000000 |
+--------+---------+-----------+
我希望得到这个结果,其中所有子组件都与其累积数量的顶级ItemNos相关:
+--------+---------+-----------+
| ItemNo | CompNo | Quantity |
+--------+---------+-----------+
| 1000 | 1100 | 2.000000 |
| 1000 | 1200 | 6.000000 |
| 2000 | 2100 | 4.000000 |
| 2000 | 2200 | 8.000000 |
+--------+---------+-----------+
答案 0 :(得分:0)
首先,项目不在compno中的值
SELECT
BL.itemno,
BL.compno,
BL.quantity
FROM
dbo.bomline BL LEFT JOIN
dbo.bomline CBL ON BL.itemno = CBL.compno
WHERE
CBL.itemno IS NULL
第一次查询的输出:
itemno compno quantity
------ ------ ---------
1000 1100 2.000000
2000 2100 4.000000
第二次查询:
SELECT
BL.itemno,
PBL.compno,
BL.quantity * PBL.quantity AS quantity
FROM
dbo.bomline BL INNER JOIN
dbo.bomline PBL ON BL.compno = PBL.itemno
第二次查询的输出:
itemno compno quantity
------ ------ ---------------
1000 1200 6.000000
2000 2200 8.000000
结果:
SELECT
BL.itemno,
BL.compno,
BL.quantity
FROM
dbo.bomline BL LEFT JOIN
dbo.bomline CBL ON BL.itemno = CBL.compno
WHERE
CBL.itemno IS NULL
UNION ALL
SELECT
BL.itemno,
PBL.compno,
BL.quantity * PBL.quantity AS quantity
FROM
dbo.bomline BL INNER JOIN
dbo.bomline PBL ON BL.compno = PBL.itemno
结果输出:
itemno compno quantity
------ ------ --------------
1000 1100 2.000000
1000 1200 6.000000
2000 2100 4.000000
2000 2200 8.000000