在GroupBy中使用递归CTE

时间:2015-07-24 21:53:14

标签: sql-server recursion common-table-expression

我是递归CTE概念的新手,手头有一个问题,我觉得这个问题可以通过使用递归CTE来解决。让我知道你们的想法。

两张桌子:

表一是自引用位置表,其中包含IDParentIDLevelDescription

表2是一个资产表,它记录了各个资产,并且具有位置表ID字段的外键。

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的存储过程,并返回该级别的所有位置记录以及该位置内的资产数量(包括子级别)。

例如,如果@Level = 3,则存储过程应返回:

ID  Description  AssetCount
5   Floor1       4   
6   Floor2       0
7   Floor3       10

如果@Level = 2,则存储过程应返回:

ID Description AssetCount
3  Building1   4    
4  Building2   10

如果问题不明确,请告诉我。

1 个答案:

答案 0 :(得分:3)

嗯,这里没什么特别的,只是一个递归的CTE加入了另一个表,结果就是你所期望的:

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

SQL Fiddle

相关问题