【发布时间】:2019-12-13 15:44:26
【问题描述】:
我正在尝试通过在层次结构中导航来执行一些计算。在下面的简单示例中,组织具有员工人数并且可以与上级组织相关联,员工人数仅为“分支”组织指定。我想使用简单的规则计算整个层次结构的人数:parent_headcount = sum(children_headcount)。
我喜欢为此使用SQL Common Table Expression 的想法,但这并不完全奏效。级别的确定有效(因为它遵循自然的自上而下的导航顺序),但不是人数确定。
您将如何解决这个问题,或者有更好的方法来执行这种自下而上的计算?
-- Define the hierachical table Org
drop table if exists Org
create table Org (
ID int identity (1,1) not null, Name nvarchar(50), parent int null, employees int,
constraint [PK_Org] primary key clustered (ID),
constraint [FK_Parent] foreign key (parent) references Org(ID)
);
-- Fill it in with a simple example
insert into Org (name, parent, employees) values ('ACME', NULL, 0);
insert into Org (name, parent, employees) values ('ACME France', (select Org.ID from Org where Name = 'ACME'), 0);
insert into Org (name, parent, employees) values ('ACME UK', (select Org.ID from Org where Name = 'ACME'), 0);
insert into Org (name, parent, employees) values ('ACME Paris', (select Org.ID from Org where Name = 'ACME France'), 200);
insert into Org (name, parent, employees) values ('ACME Lyons', (select Org.ID from Org where Name = 'ACME France'), 100);
insert into Org (name, parent, employees) values ('ACME London', (select Org.ID from Org where Name = 'ACME UK'), 150);
select * from Org;
-- Try to determine the total number of employees at any level of the hierarchy
with Orgs as (
select
ID, name, parent, 0 as employees, 0 as level from Org where parent is NULL
union all
select
child.ID, child.name, child.parent, Orgs.employees + child.employees, level + 1 from Org child
join Orgs on child.parent = Orgs.ID
)
select * from Orgs;
此查询返回:
级别的确定是正确的,但人数的计算不正确(英国应该是 150,法国应该是 300,450 在层级的顶部)。好像CTE适合自上而下的导航,不适合自下而上的导航?
【问题讨论】:
标签: sql sql-server hierarchy