【问题标题】:Using Recursive CTE with GroupBy将递归 CTE 与 GroupBy 一起使用
【发布时间】:2015-07-24 21:53:13
【问题描述】:

我是递归 CTE 概念的新手,手头有一个问题,我有一种小小的感觉,即使用递归 CTE 可以解决问题。让我知道你们的想法。

两个表:

表一是带有IDParentIDLevelDescription 的自引用位置表。

表二是一个资产表,它记录了单个资产,并有一个外键指向位置表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

如果问题不清楚,请告诉我。

【问题讨论】:

  • 我不确定我理解为什么你需要递归地做某事。你问的不等于select a.ID, a.Description, b.Quantity as AssetCount from table1 a inner join table2 b on a.id = b.id where a.level = @level吗?
  • @Xedni 不是。需要递归来获取每个父级的子行;您的示例查询只会对父 ID 的数量求和,而不包括子 ID。
  • Xedni 感谢您的建议,但我认为 jpw 是正确的,JamesZ 提供的答案是正确的,这是一种获得结果的优雅方式!我只能想到使用临时表的方法......

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


【解决方案1】:

嗯,这里没什么特别的,只是一个递归 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

【讨论】:

  • 问题似乎已解决,但我还是不喜欢使用递归CTE,你可以看看here
  • @TirthakShah 为了能够在没有递归的情况下做到这一点,您必须拥有固定数量的级别,并为每个级别单独加入表格 - 为了提高性能,您可能必须为每个级别参数创建单独的分支以摆脱额外的表
猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 2020-10-22
  • 2020-10-11
相关资源
最近更新 更多