MSSQL:左连接三个表中的多个列

MSSQL: left join multiple columns in three tables

我在 MS SQL 中有三个 table 服务器:

Tenants:
TenantID int,
LastName varchar(50),
FirstName varchar(50)

Intervals:
Value int,
Name varchar(50)

Leases:
LeaseID int,
Interval int,
StartDate date,
EndDate date,
Tenant1 int,
Tenant2 int,
Tenant3 int,
Tenant4 int

间隔 table 有三行:[1,'Monthly']、[2,'BiWeekly'] 和 [3,'Weekly']

我需要一个具有此结果集的查询:

LID Type      Start         End      Tenant1       Tenant2        Tenant3       Tenant4
21  Monthly  12/15/2019  12/15/2020  Sean Murphy   Audrey Moore   Randy Davis
32  Weekly   06/01/2018              Pete Higgins  Kathy Higgins  
35  Monthly  08/01/2019  10/31/2020  Andy Stacke   Valerie Stacke
44  Monthly  01/01/2021              Pete O'Toole  Martha White   

暂且不考虑 firstname+lastname 列,我的第一次尝试成功地使用了两个左连接:

select L.LeaseID, I.Name as Type, L.StartDate, L.EndDate, T.LastName as Tenant1 
from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Tenant1

并返回了这个:

LID Type      Start         End      Tenant1 
21  Monthly  12/15/2019  12/15/2020  Murphy  
32  Weekly   06/01/2018              Higgins
35  Monthly  08/01/2019  10/31/2020  Stacke
44  Monthly  01/01/2021              O'Toole

一个好的开始,但我似乎无法从租户那里得到最多 4 个唯一的名字 table,我想在租户列中组合 (firstname+lastname)。

我为同一个 table(租户)尝试了多个左连接,并在一个连接上尝试了 ORing 条件;直觉上他们似乎都错了。

select L.lid,L.ruid, I.Name, T.LastName as Tenant1, T.LastName as Tenant2 from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Ten1
left join Tenants T on T.TID = L.Ten2

select L.lid,L.ruid, I.Name, T.LastName as Tenant1, T.Lastname as Tenant2 from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Ten1 or T.TID = L.Ten2  

但是这两个在两列中返回了相同的姓氏。

试试这个

select
  L.lid
  ,L.ruid
  , I.Name
  , T1.LastName as Tenant1
  , T2.LastName as Tenant2 
from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T1 on T1.TID = L.Ten1
left join Tenants T2 on T2.TID = L.Ten2

在这里没有网络工作,但我相信你想要这样的东西:

select 
    L.LeaseID AS 'LID', 
    I.Name AS 'Type', 
    L.StartDate AS 'Start', 
    L.EndDate AS 'End', 
    CONCAT(T1.FirstName, ' ', T1.LastName) AS 'Tenant1', 
    CONCAT(T2.FirstName, ' ', T2.LastName) AS 'Tenant2', 
    CONCAT(T3.FirstName, ' ', T3.LastName) AS 'Tenant3', 
    CONCAT(T4.FirstName, ' ', T4.LastName) AS 'Tenant4'
from Leases L
left join Intervals I ON L.Interval = I.Value
left join Tenants T1 ON L.Tenant1 = T1.TenantID
left join Tenants T2 ON L.Tenant2 = T2.TenantID
left join Tenants T3 ON L.Tenant3 = T3.TenantID
left join Tenants T4 ON L.Tenant4 = T4.TenantID