嵌套表元素查询



MSSQL我有T1带有Idname列的表格。就像上一个问题一样,但还有另一个任务。

T2 包含Aggregate_IDElement_ID

他们被交叉

x1:

ID и Name
1 Car
2 Hood
3 Engine
4 Cylinder 
5 Wheel
6 tyre
7 rim (car)
8 Rim fixation (Car)

x2:

Aggregate_ID Element_ID
1 2
1 3 
1 5 
3 4
5 6
5 7
7 8 

我需要输出所有最简单的元素,其中由像 Wheel 这样的聚合组成。在轮子的情况下,这将是 6,8。"汽车"将是 2,4,6,8可以更改嵌套的级别。这是一个简单的例子。但是嵌套级别可以是 4,5..20 或无限制。

我读了这个 http://technet.microsoft.com/ru-ru/library/ms186243(v=sql.105(.aspx但现在我无法处理它

您可以使用以下查询。它使用公用表表达式。第一部分获取作为参数的聚合。第二部分以递归方式添加下一个聚合。

然后我选择那些是这棵树的叶子的聚集体(不是父母(。

declare @part as varchar(max) = 'wheel'
;with cte
as
(
    select aggregate_id, element_id
    from t2 where aggregate_id = (select id from t1 where name = @part)
    union all
    select t2.aggregate_id, t2.element_id
    from t2
    inner join cte on cte.element_id = t2.aggregate_id
)
select distinct c1.element_id from cte c1
where not exists (select * from cte c2 where c1.element_id = c2.aggregate_id)

最新更新