基于以下输出
我想汇总祖先级别的金额,即城市/州/国家。例如:在上面的示例中,我们有国家 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