22,300
社区成员




create table sx
(父级 varchar(5),子级 varchar(5),用量 int)
insert into sx
select 'A','B',1 union all
select 'B','C',2 union all
select 'C','D',1 union all
select 'B1','C1',1 union all
select 'X','B',2 union all
select 'X','B1',2
;with t as
(select a.父级 '顶层',a.子级,a.用量
from sx a
where not exists(select 1 from sx b where b.子级=a.父级)
union all
select d.顶层,c.子级,c.用量*d.用量
from sx c
inner join t d on c.父级=d.子级
)
select a.顶层,a.子级,a.用量,
case when not exists(select 1 from sx b where b.父级=a.子级)
then '底层' else '' end '标识'
from t a
order by a.顶层;
create table sx
(父级 varchar(5),子级 varchar(5),用量 int)
insert into sx
select 'A','B',1 union all
select 'B','C',2 union all
select 'C','D',1 union all
select 'B1','C1',1 union all
select 'X','B',2 union all
select 'X','B1',2
with t as
(select a.父级 '顶层',a.子级,a.用量
from sx a
where not exists(select 1 from sx b where b.子级=a.父级)
union all
select d.顶层,c.子级,c.用量*d.用量
from sx c
inner join t d on c.父级=d.子级
)
select a.顶层,a.子级,a.用量,
case when not exists(select 1 from sx b where b.父级=a.子级)
then '底层' else '' end '标识'
from t a
order by a.顶层
/*
顶层 子级 用量 标识
----- ----- ----------- ----
A B 1
A C 2
A D 2 底层
X B 2
X B1 2
X C1 2 底层
X C 4
X D 4 底层
(8 row(s) affected)
*/