简体   繁体   中英

SQL Server : join on 4-5 tables with different structures

I have three tables

  • Employee
  • ApprovalMatrix
  • ExpenseMatrix

Employee contains:

ID  CompanyId  Name
---------------------------------------
9   1          ABC  
10  1          XYZ
11  1          WEW 

ApprovalMatrix contains:

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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM