sql - SQL Server 中的自联接
问题描述
我在 SQL Server 中有两个表:
Employee (Parent):
EMPID | EMPNAME | ROLE | DEPTID
1 | John | Manager | M1
2 | George | Employee | E1
3 | Alex | Intern | I1
4 | Bob | Employee | E2
REL (It holds Emp to Emp relationship):
FROM_EID | TO_EID
1 | 2
2 | 3
预期输出:
RELATED_ID
M1-E1-I1
我正在使用以下查询来获取 EMPID 1、2 和 3 的详细信息,以便稍后连接 DEPTID:
select * from REL rel1, REL rel2, REL rel3
where rel1.FROM_EID = rel2.TO_EID
and rel2.FROM_EID = rel3.TO_EID;
但我没有在这里获得 EMPID #1 的详细信息。我怎样才能做到这一点?
解决方案
干得好:
with
x as (
select
empid as startid, 0 as level,
empid, cast(concat('', deptid) as varchar(255)) as chain
from employee where empid = 1
union all
select
x.startid, x.level + 1,
e.empid, cast(concat(chain, '-', e.deptid) as varchar(255))
from x
join rel r on r.from_eid = x.empid
join employee e on e.empid = r.to_eid
),
y as (
select startid, max(level) as max_level from x group by startid
)
select x.chain
from x
join y on x.startid = y.startid and x.level = y.max_level
结果:
chain
--------
M1-E1-I1
作为参考,我使用的数据脚本是:
create table employee (
empid int,
empname varchar(10),
role varchar(10),
deptid varchar(10)
);
create table rel (
from_eid int,
to_eid int
);
insert into employee (empid, empname, role, deptid) values
(1, 'John', 'Manager', 'M1'), (2, 'George', 'Employee', 'E1'),
(3, 'Alex', 'Intern', 'I1'), (4, 'Bob', 'Employee', 'E2');
insert into rel (from_eid, to_eid) values
(1, 2), (2, 3);
推荐阅读
- angular - 使用 ng-template、ng-container 和 ngTemplateOutlet 设置输入模板的上下文
- database - Laravel 添加 CLOB 列
- python - 如何在 python 上打包数组 iwht msgpack?
- reactjs - 从 Accordion 列表中的 api 获取数据 react native
- tensorflow - Keras 和带有 dropout 的 LSTM 的 tensorflow 实现之间的区别
- r - 在 R 中运行两个循环以进行数学表达式计算
- php - Laravel 对表单验证的大会话值有错误
- javascript - TypeError: undefined is not an object (evalating 'XYZ') - JavaScript
- cassandra - 更新整个 Cassandra 表的列值的实用解决方法
- javascript - 如何在悬停时禁用闪烁动作 - CSS3