首页 > 解决方案 > 如何根据职位层次结构获取组织单位的层次关系

问题描述

我有一个包含一些 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 数据库中获取此信息?

标签: sqlsql-servertsql

解决方案


利用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

输出:

org_id  parentorgid
A   
B         A
C         A
B1        B
B2        B
C1        C

推荐阅读