EID PID Name
1 NULL A
2 1 B
3 2 C
4 3 D
5 1 E
6 1 F
7 1 G
8 6 H
上面的信息显示了一个表的实际数据,我想在下表中显示该表中的数据。
即。使用EID和PID的数据层次结构显示。
这里PID表示ParentID,EID是EntityID,使用ParentID需要获取Hierarchy,如下所示。
Level1 Level2 Level3 Level4
A NULL NULL NULL
A B NULL NULL
A B C NULL
A B C D
A E NULL NULL
A F NULL NULL
A F H NULL
A G NULL NULL
答案 0 :(得分:1)
因为您知道级别数,所以可以使用left join
:
select l1.name as level1, l2.name as level2,
l3.name as level3, l4.name as level4
from data l1 left join
data l2
on l2.pid = l1.id left join
data l3
on l3.pid = l2.id left join
data l4
on l4.pid = l3.id;
答案 1 :(得分:0)
免责声明:这是( MS-SQL )中的一个示例
@Gordon Linoff回答几乎做到了,只是忘了基本情况( Pid为空)
只需按照左连接+联合的这种模式覆盖固定数量级别的基本情况,对于不需要使用递归的动态数字操作系统级别
declare @Tree as
table (
Eid int not null
,Pid int null
,Name char(1) not null
)
insert into @Tree
values
(1, NULL, 'A')
,(2, 1, 'B')
,(3, 2, 'C')
,(4, 3, 'D')
,(5, 1, 'E')
,(6, 1, 'F')
,(7, 1, 'G')
,(8, 6, 'H')
(
select t1.Name as [Level 1], null as [Level 2], null as [Level 3], null as [Level 4]
from @Tree t1
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], null as [Level 3], null as [Level 4]
from @Tree t1
left join @Tree t2 on t2.Pid = t1.Eid
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], t3.Name as [Level 3], null as [Level 4]
from @Tree t1
left join @Tree t2 on t2.Pid = t1.Eid
left join @Tree t3 on t3.Pid = t2.Eid
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], t3.Name as [Level 3], t4.Name as [Level 4]
from @Tree t1
left join @Tree t2 on t2.Pid = t1.Eid
left join @Tree t3 on t3.Pid = t2.Eid
left join @Tree t4 on t4.Pid = t3.Eid
where t1.Pid is null
) order by [Level 1], [Level 2], [Level 3], [Level 4]
编辑以及使用右连接而不是左连接的相同查询
declare @Tree as
table (
Eid int not null
,Pid int null
,Name char(1) not null
)
insert into @Tree
values
(1, NULL, 'A')
,(2, 1, 'B')
,(3, 2, 'C')
,(4, 3, 'D')
,(5, 1, 'E')
,(6, 1, 'F')
,(7, 1, 'G')
,(8, 6, 'H')
(
select t1.Name as [Level 1], null as [Level 2], null as [Level 3], null as [Level 4]
from @Tree t1
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], null as [Level 3], null as [Level 4]
from @Tree t2
right join @Tree t1 on t2.Pid = t1.Eid
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], t3.Name as [Level 3], null as [Level 4]
from @Tree t3
right join @Tree t2 on t3.Pid = t2.Eid
right join @Tree t1 on t2.Pid = t1.Eid
where t1.Pid is null
union
select t1.Name as [Level 1], t2.Name as [Level 2], t3.Name as [Level 3], t4.Name as [Level 4]
from @Tree t4
right join @Tree t3 on t4.Pid = t3.Eid
right join @Tree t2 on t3.Pid = t2.Eid
right join @Tree t1 on t2.Pid = t1.Eid
where t1.Pid is null
) order by [Level 1], [Level 2], [Level 3], [Level 4]