27,579
社区成员
发帖
与我相关
我的任务
分享
with tb(单位,级别,上级单位)
as(
select N'A公司',1,NULL union all
select N'B公司',2,N'A公司' union all
select N'C公司',3,N'B公司' union all
select N'D公司',3,N'B公司'
),cte as(
select *,lvl=0 from tb where 上级单位 is null
union all
select t.*,lvl+1 as lvl from tb t inner join cte c on t.上级单位=c.单位
)
select REPLICATE(' ',lvl*2 )+ 单位,级别,上级单位 from cte
(No column name) 级别 上级单位
1 A公司 1 NULL
2 B公司 2 A公司
3 C公司 3 B公司
4 D公司 3 B公司
with tb(单位,级别,上级单位)
as(
select 'A公司',1,NULL union all
select 'B公司',2,'A公司' union all
select 'C公司',3,'B公司' union all
select 'D公司',3,'B公司'
),cte as(
select *,lv=cast ('' as varchar(50)) from tb where isnull(上级单位,'')='' union all
select t.*,cast(lv+'1' as varchar(50)) from tb t,cte c where t.上级单位=c.单位
)
select replace(lv,'1',' ')+单位 from cte