我有一张员工表emp
,如下所示:
emp_id emp_name emp_role
______________________________
1 aaaa Supervisor
2 bbbb Supervisor
3 cccc helper
4 dddd helper
5 eeee helper
6 ffff helper
另一个表Supervisor
和辅助映射(Sup_Helper_Map
):
supervisor_id helper_id
____________________________
1 3
1 4
2 5
2 6
如果可能,我希望在单个查询中使用以下结构中的数据,例如,。
Supervisor_id Supervisor_name helper_id helper_name
_______________________________________________________________
1 aaaa 3 cccc
1 aaaa 4 dddd
2 bbbb 5 eeee
2 bbbb 6 ffff
答案 0 :(得分:1)
你可以简单地加入Employee
表2次,以获得预期的结果。
使用给定的样本数据进行演示:
DECLARE @Employee TABLE (emp_id INT, emp_name VARCHAR (100), emp_role VARCHAR (100));
INSERT INTO @Employee (emp_id, emp_name, emp_role) VALUES
(1, 'aaaa', 'Supervisor'),
(2, 'bbbb', 'Supervisor'),
(3, 'cccc', 'helper'),
(4, 'dddd', 'helper'),
(5, 'eeee', 'helper'),
(6, 'ffff', 'helper');
DECLARE @Sup_Helper_Map TABLE (Supervisor_id INT, Helper_id INT);
INSERT INTO @Sup_Helper_Map (Supervisor_id, Helper_id) VALUES
(1, 3),
(1, 4),
(2, 5),
(2, 6);
SELECT M1.Supervisor_id, E1.emp_name AS Supervisor_name,
M1.Helper_id, E2.emp_name AS Helper_name
FROM @Sup_Helper_Map M1
JOIN @Employee E1 ON E1.emp_id = M1.Supervisor_id
JOIN @Employee E2 ON E2.emp_id = M1.Helper_id
结果:
Supervisor_id Supervisor_name Helper_id Helper_name
--------------------------------------------------------
1 aaaa 3 cccc
1 aaaa 4 dddd
2 bbbb 5 eeee
2 bbbb 6 ffff
答案 1 :(得分:0)
试试这个
SELECT
s.supervisor_id,
e.emp_name supervisor_Name,
s.helper_id,
h.emp_name helper_name
FROM
emp e INNER JOIN
Sup_Helper_Map s ON e.emp_id = s.supervisor_id INNER JOIN
emp h ON s.helper_id = h.emp_id
答案 2 :(得分:0)
SELECT dbo.Sub_Helper_Map.supervisor_id, emp1_1.emp_name AS Supervisor_name, dbo.Sub_Helper_Map.helper_id, dbo.emp.emp_name AS helper_name
FROM dbo.emp INNER JOIN
dbo.Sub_Helper_Map ON dbo.emp.emp_id = dbo.Sub_Helper_Map.helper_id INNER JOIN
dbo.emp AS emp1_1 ON dbo.Sub_Helper_Map.supervisor_id = emp1_1.emp_id