我如何构建这个三级层次结构查询,
How can i construct this three level hierarchy Query,
我有一个场景。
我有 sql 服务器 table 结构如下
ID CodeLevel ParentID Name
----------- ----------- ----------- --------------------------------------------------
1 1 NULL Company Group
40 2 1 Corp Fun
41 3 40 Fin
45 4 41 Cont
48 4 41 CFO
51 4 41 Inv Rel
52 4 41 CTandC
94 3 40 COffice
95 4 94 CEOffice
我正在寻找一个查询来获取业务单位、业务部门和业务组。例如:CodeLevel = 4 都是 Business Units.
现在,对于 ID = 95,名称是 CEOoffice。 CEO办公室是BusinessUnit
对于ID = 95,ParentID为94。对于ID=94,Name为COFfice即事业部
对于ID=94,它的专利ID是40。所以,ID=40,名称是Corp Fun,也就是BusinessGroup。
因此,当 ID = 51 时:
- BusinessUnit 是 Inv Rel
- BusinessDivision 是 Fin
- BusinessGroup 是 Corp Fun
请帮我写这个查询。谢谢
只有两个连接
select base.ID, base.Name, div.Name, grp.Nave
from table as base
join table as div
on div.ID = base.parentID
and base.ID = 51
join table as grp
on grp.ID = div.parentID
我有一个场景。
我有 sql 服务器 table 结构如下
ID CodeLevel ParentID Name
----------- ----------- ----------- --------------------------------------------------
1 1 NULL Company Group
40 2 1 Corp Fun
41 3 40 Fin
45 4 41 Cont
48 4 41 CFO
51 4 41 Inv Rel
52 4 41 CTandC
94 3 40 COffice
95 4 94 CEOffice
我正在寻找一个查询来获取业务单位、业务部门和业务组。例如:CodeLevel = 4 都是 Business Units.
现在,对于 ID = 95,名称是 CEOoffice。 CEO办公室是BusinessUnit
对于ID = 95,ParentID为94。对于ID=94,Name为COFfice即事业部
对于ID=94,它的专利ID是40。所以,ID=40,名称是Corp Fun,也就是BusinessGroup。
因此,当 ID = 51 时:
- BusinessUnit 是 Inv Rel
- BusinessDivision 是 Fin
- BusinessGroup 是 Corp Fun
请帮我写这个查询。谢谢
只有两个连接
select base.ID, base.Name, div.Name, grp.Nave
from table as base
join table as div
on div.ID = base.parentID
and base.ID = 51
join table as grp
on grp.ID = div.parentID