1

基于以下输出

在此处输入图像描述

我想汇总祖先级别的金额,即城市/州/国家。例如:在上面的示例中,我们有国家 Australia 和两个州(VIC 和 NSW)。维多利亚州有两个城市(墨尔本和本迪戈),新南威尔士州没有城市。查询的结果应该显示完全相同数量的记录,但在祖先级别汇总数量。比如说,墨尔本应该显示 800,VIC 应该显示 1300,澳大利亚应该显示 2500,如下所示:

在此处输入图像描述

是否可以使用层次结构的 GetAncestor 函数使用递归 CTE 来做到这一点?

CREATE TABLE #Test ( EmployeeNode hierarchyid, EmployeeName varchar(50), Location varchar(50), Amount decimal )

ALTER TABLE #Test ADD [Level] as EmployeeNode.GetLevel()

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/' AS hierarchyid), 'Australia', NULL, NULL)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/' AS hierarchyid), 'VIC', NULL, NULL)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/1/' AS hierarchyid), 'Melbourne', NULL, NULL)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/1/1/' AS hierarchyid), NULL, 'Mary', 300.00)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/1/2/' AS hierarchyid), NULL, 'Timothy', 500.00)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/2/' AS hierarchyid), 'Bendigo', NULL, NULL)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/1/2/1/' AS hierarchyid), NULL, 'Paul', 500.00)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/2/' AS hierarchyid), 'NSW', NULL, NULL)

INSERT INTO #Test (EmployeeNode, Location, EmployeeName, Amount) VALUES (CAST('/0/2/1/' AS hierarchyid), 'NSW', 'Peter', 1200.00)

SELECT t.EmployeeNode.ToString(), t.* FROM #Test t

4

1 回答 1

2
declare @Test as Table ( EmployeeNode HierarchyId, EmployeeName VarChar(50), Location VarChar(50), Amount Decimal );

insert into @Test ( EmployeeNode, Location, EmployeeName, Amount ) values
  ( Cast( '/0/' as HierarchyId ), 'Australia', NULL, NULL ),
  ( Cast( '/0/1/' as HierarchyId ), 'VIC', NULL, NULL ),
  ( Cast( '/0/1/1/' as HierarchyId ), 'Melbourne', NULL, NULL ),
  ( Cast( '/0/1/1/1/' as HierarchyId ), NULL, 'Mary', 300.00 ),
  ( Cast( '/0/1/1/2/' as HierarchyId ), NULL, 'Timothy', 500.00 ),
  ( Cast( '/0/1/2/' as HierarchyId ), 'Bendigo', NULL, NULL ),
  ( Cast( '/0/1/2/1/' as HierarchyId ), NULL, 'Paul', 500.00 ),
  ( Cast( '/0/2/' as HierarchyId ), 'NSW', NULL, NULL ),
  ( Cast( '/0/2/1/' as HierarchyId ), 'NSW', 'Peter', 1200.00 );

select EmployeeNode.ToString(), *, EmployeeNode.GetLevel() as [Level],
  ( select Sum( Amount )
      from @Test where EmployeeNode.IsDescendantOf( P.EmployeeNode ) = 1 ) as [Total]
  from @Test as P;
于 2013-05-24T00:26:03.193 回答