将递归 CTE 与 GroupBy 结合使用
Using Recursive CTE with GroupBy
我是递归 CTE 概念的新手,手头有一个问题,我有一点感觉可以通过使用递归 CTE 来解决这个问题。让我知道你们的想法。
两个table:
Table 一个是自引用位置 table 与 ID
、ParentID
、Level
和 Description
。
Table二是一个资产table,它记录了单个资产,并且有一个指向位置tableID
字段的外键。
Table1:
ID Description ParentID Level
1 Site1 NULL 1
2 Site2 NULL 1
3 Building1 1 2
4 Building2 1 2
5 Floor1 3 3
6 Floor2 3 3
7 Floor3 4 3
8 Place1 5 4
9 Place2 7 4
Table2:
ID Description Quantity LocationID
1 Desk 3 8
2 Lamp 1 8
3 PC 10 9
我想创建一个存储过程,其输入参数为 @Level
和 return 该级别的所有位置记录以及该位置内的资产数量(包括子级别) .
例如,如果@Level = 3,存储过程应该return:
ID Description AssetCount
5 Floor1 4
6 Floor2 0
7 Floor3 10
如果@Level = 2,存储过程应该return:
ID Description AssetCount
3 Building1 4
4 Building2 10
如果问题不清楚,请告诉我。
好吧,这里没什么特别的,只是将递归 CTE 与另一个 table 相结合,结果如您所料:
declare @level int = 3
;with CTE as (
select id as origid, id, Description, parentid
from table1 where level = @level
union all
select CTE.origid, t1.id, CTE.Description, t1.parentid
from CTE join table1 t1 on
CTE.id = t1.parentid
)
select origid, CTE.description, isnull(sum(t2.Quantity),0) as Quantity
from CTE left outer join table2 t2 on CTE.id = t2.locationid
group by origid, CTE.description
我是递归 CTE 概念的新手,手头有一个问题,我有一点感觉可以通过使用递归 CTE 来解决这个问题。让我知道你们的想法。
两个table:
Table 一个是自引用位置 table 与 ID
、ParentID
、Level
和 Description
。
Table二是一个资产table,它记录了单个资产,并且有一个指向位置tableID
字段的外键。
Table1:
ID Description ParentID Level
1 Site1 NULL 1
2 Site2 NULL 1
3 Building1 1 2
4 Building2 1 2
5 Floor1 3 3
6 Floor2 3 3
7 Floor3 4 3
8 Place1 5 4
9 Place2 7 4
Table2:
ID Description Quantity LocationID
1 Desk 3 8
2 Lamp 1 8
3 PC 10 9
我想创建一个存储过程,其输入参数为 @Level
和 return 该级别的所有位置记录以及该位置内的资产数量(包括子级别) .
例如,如果@Level = 3,存储过程应该return:
ID Description AssetCount
5 Floor1 4
6 Floor2 0
7 Floor3 10
如果@Level = 2,存储过程应该return:
ID Description AssetCount
3 Building1 4
4 Building2 10
如果问题不清楚,请告诉我。
好吧,这里没什么特别的,只是将递归 CTE 与另一个 table 相结合,结果如您所料:
declare @level int = 3
;with CTE as (
select id as origid, id, Description, parentid
from table1 where level = @level
union all
select CTE.origid, t1.id, CTE.Description, t1.parentid
from CTE join table1 t1 on
CTE.id = t1.parentid
)
select origid, CTE.description, isnull(sum(t2.Quantity),0) as Quantity
from CTE left outer join table2 t2 on CTE.id = t2.locationid
group by origid, CTE.description