我有一个表,其中包含一些HR数据,包括(其他详细信息)职位ID,上级职位ID和组织单位ID。
类似
pos_id | parent_pos_id | pos_name | org_id | org_name
1 | null | CEO | A | Executive
2 | 1 | Assistant | A | Executive
3 | 1 | IT Director | B | Information Technology
4 | 1 | Finances Director | C | Finances
5 | 3 | Systems Leader | B | Information Technology
6 | 5 | Database Manager | B1 | Database Systems
7 | 5 | Application Manager | B2 | OS and Applications
8 | 4 | Finances Leader | C | Finances
9 | 4 | Financial Assistant | C | Finances
10 | 8 | Payroll Manager | C1 | Payroll
,并且我需要基于位置层次关系获取每个记录的父组织单位ID的信息。
因此,对于上面的示例,所需的输出将是:
org_id | parent_org_id
A | null
B | A
C | A
B1 | B
B2 | B
C1 | C
是否可以构建查询以在SQL Server数据库中获取此查询?
答案 0 :(得分:1)
使用// this line is in my server.js
app.use( express.static( path.join( __dirname, 'public' ) ) )
self join
输出:
select a.org_id as org_id,b.org_id as parentorgid
from t1 a
left join t1 b on a.parent_pos_id=b.pos_id
where a.org_id<>b.org_id or b.org_id is null
答案 1 :(得分:1)
您需要为此编写一个递归CTE,伪代码在下面
with cte as
(
select org_id,parentorg_id,pos_id,parentpos_id from hrtable where parentpos_id is null
UNION ALL
select org_id,parentorg_id,pos_id,parentpos_idfrom hrtable t join cte c on t.parentpso_id=c.pos_id
)
select org_id,parentorg_id from cte c