[英]SQL Server : join on 4-5 tables with different structures
I have three tables 我有三张桌子
Employee
contains: Employee
包含:
ID CompanyId Name
---------------------------------------
9 1 ABC
10 1 XYZ
11 1 WEW
ApprovalMatrix
contains: ApprovalMatrix
包含:
ID Module Employeeid EmployeeLeaderId
--------------------------------------------
11 M1 9 11
12 M1 10 11
13 M2 9 11
55 M3 10 11
56 M2 10 11
ExpenseMatrix
contains: ExpenseMatrix
包含:
ID Employeeid EmployeeLeaderId
--------------------------------------------
11 10 9
12 11 9
Expected result: 预期结果:
Module EmployeeName EmployeeLeaderName
--------------------------------------------
M1 ABC WEW
M1 XYX WEW
M2 ABC WEW
M3 XYZ WEW
M2 XYZ WEW
Expense XYZ ABC
Expense WEW ABC
Like this I have 4-5 different tables need to merge all tables Employee wise, also need module name for which module leader is assigned. 像这样,我有4-5个不同的表需要合并所有表Employee,也需要为其分配模块领导者的模块名称。
Below is the query I have tried so far 以下是我到目前为止尝试过的查询
select
C.Module, A.Employeeid, B.Name
from
Employee B
join
ExpenseMatrix A on A.EmployeeLeaderId = B.Id
join
ApprovalMatrix C on C.EmployeeLeaderId = B.Id
where
B.EmpStatus = 1 and A.EmployeeId = 56
select
A.Module, e1.name, e2.Name
from
ApprovalMatrix AM
inner join Employee E1
on AM.EmployeeId = E1.ID
inner join Employee E2
on AM.EmployeeLeaderId = E2.ID
union all
select 'Expense', e1.name, e2.name
From ExpenseMatrix EM
inner join Employee E1
on EM.EmployeeId = E1.ID
inner join Employee E2
on EM.EmployeeLeaderId = E2.ID
Hi try below code . 嗨,尝试下面的代码。
;with temp as
(select Module , Employeeid , EmployeeLeaderId from ApprovalMatrix
union all
select 'Expence' as Module ,Employeeid , EmployeeLeaderId from ExpenseMatrix )
select Module, b.Name as EmployeeName ,c.name as EmployeeLeaderName from temp a
left join Employee b on a.EmployeeLeaderId =b.Id
left join Employee c on a.EmployeeLeaderId =c.id
Note Add more table in union all in CTE block. 注意在CTE块中的union中添加更多表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.