sql - 如何根据职位层次结构获取组织单位的层次关系
问题描述
我有一个包含一些 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 数据库中获取此信息?
解决方案
利用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
推荐阅读
- r - 尝试在测试数据集上使用 model.matrix 函数
- javascript - Angular Route Guard - 未正确重定向到登录页面
- rust - 如何将带有顶层表的 TOML 文件解析为 Rust 结构?
- java - Java Streams:扩展内置收集器
- c# - 返回到 UWP XAML 页面 ContentDialog.RunAsync() 后导致“值不在预期范围内。”
- c - Linux 内核如何设置 PCI BAR 以保证没有地址冲突?
- unity3d - Unity - 如何通过相机移动放大和缩小?
- asp.net - 计数器变量在 Asp.net 网络表单中不起作用?
- python - 修复数据框中超出 CSV 字段长度的额外字段
- node.js - 如何从 bot 内部向 Microsoft bot 发送消息,以便消息通过对话流并获得相应的响应?