表A Employee_ID(类型A) 员工姓名 员工编号(B型) 员工姓名
表B Employee_ID(任何类型) Employee_MGR
我需要通过查询 Table C 如下(无需表格,无需创建视图)
Employee_ID(类型A) 员工姓名 员工_MGR 员工编号(B型) 员工姓名 Employee_MGR
答案 0 :(得分:0)
您只需要两次加入经理表,每种雇员ID类型一次。
如果我不指出这是一个糟糕的数据模型,我会很失落,但是我确定您已经知道了。
设置表格:
DECLARE @TableA TABLE
(
[Employee_ID(Type A)] INT
,[Employee_Name] VARCHAR(20)
,[Employee_ID(Type B)] INT
,[Employee Name] VARCHAR(20)
);
INSERT
@TableA
(
[Employee_ID(Type A)]
,Employee_Name
,[Employee_ID(Type B)]
,[Employee Name]
)
VALUES
(1,'Bob',2,'Robert')
,(3,'Sue',4,'Susan');
DECLARE @TableB TABLE
(
[Employee_ID(Any Type)] INT
,[Employee_MGR] VARCHAR(20)
);
INSERT
@TableB
(
[Employee_ID(Any Type)]
,Employee_MGR
)
VALUES
(1,'Mary')
,(2,'Helen')
,(3,'Joe')
,(4,'Harry');
DECLARE @tableC TABLE
(
[Employee_ID(Type A)] INT
,[Employee_Name] VARCHAR(20)
,[Employee_MGR(Type A)] VARCHAR(20)
,[Employee_ID(Type B)] INT
,[Employee Name] VARCHAR(20)
,[Employee_MGR(Type B)] VARCHAR(20)
);
这是您的最终查询:
INSERT
@tableC
(
[Employee_ID(Type A)]
,Employee_Name
,[Employee_MGR(Type A)]
,[Employee_ID(Type B)]
,[Employee Name]
,[Employee_MGR(Type B)]
)
SELECT
emp.[Employee_ID(Type A)]
,emp.Employee_Name
,mgrA.Employee_MGR
,emp.[Employee_ID(Type B)]
,emp.[Employee Name]
,mgrB.Employee_MGR
FROM
@TableA AS emp
JOIN
@TableB AS mgrA
ON
mgrA.[Employee_ID(Any Type)] = emp.[Employee_ID(Type A)]
JOIN
@TableB AS mgrB
ON
mgrB.[Employee_ID(Any Type)] = emp.[Employee_ID(Type B)];
这就是给你的东西:
SELECT
*
FROM
@tableC;
+---------------------+---------------+----------------------+---------------------+---------------+----------------------+
| Employee_ID(Type A) | Employee_Name | Employee_MGR(Type A) | Employee_ID(Type B) | Employee Name | Employee_MGR(Type B) |
+---------------------+---------------+----------------------+---------------------+---------------+----------------------+
| 1 | Bob | Mary | 2 | Robert | Helen |
| 3 | Sue | Joe | 4 | Susan | Harry |
+---------------------+---------------+----------------------+---------------------+---------------+----------------------+