这是我要使用递归T-SQL
查询(大概是CTE
)与以下预期结果进行搜索的程序集树。我想知道给定零件的每个组件的总数。
这意味着如果我搜索“铆钉”,我想知道装配体中每个级别的总数量,而不仅仅是直接子数量。
Assembly (id:1)
|
|-Rivet
|-Rivet
|-SubAssembly (id:2)
| |
| |-Rivet
| |-Bolt
| |-Bolt
| |-SubSubAssembly (id:3)
| |
| |-Rivet
| |-Rivet
|
|-SubAssembly (id:4)
|-Rivet
|-Bolt
DESIRED Results
-------
ID, Count
1 , 6
2 , 3
3 , 2
4 , 1
目前,我可以得到直系父母,但想知道如何扩展我的CTE,以使我可以将此信息向上滚动。
With DirectParents AS(
--initialization
Select InstanceID, ParentID
From Instances i
Where i.Part = 'Rivet'
UNION ALL
--recursive execution
Select i.InstanceID, i.ParentID
From PartInstances i INNER JOIN DirectParents p
on i.ParentID = p.InstanceID
)
select ParentID, Count(instanceid) as Totals
from DirectParents
group by InstanceID, ParentID
Results
-------
ID, Count
1 , 2
2 , 2
3 , 2
4 , 1
创建脚本
CREATE TABLE [dbo].[Instances] (
[InstanceID] NVARCHAR (50) NOT NULL,
[Part] NVARCHAR (50) NOT NULL,
[ParentID] NVARCHAR (50) NOT NULL, );
INSERT INTO Instances
Values
(1, 'Assembly', 0),
(50, 'Rivet', 1),
(50, 'Rivet', 1),
(2, 'SubAssembly', 1),
(50, 'Rivet', 2),
(51, 'Bolt', 2),
(51, 'Bolt', 2),
(3, 'SubSubAssembly', 2),
(50, 'Rivet', 3),
(50, 'Rivet', 3),
(4, 'SubAssembly2', 1),
(50, 'Rivet', 4),
(51, 'Bolt', 4)