您需要添加两次 ManagementAccountLookup/Management 组合才能在一行中获取信息。如果需要,我已将LevelID
标准直接放在 join 中,以减轻可能过渡到 left-joins 的难度。
select Account.AccountID,
m_brand.Name Brand,
m_region.Name Region
from Account
inner join ManagementAccountLookup mal_brand
on Account.AccountID = mal_brand.AccountID
inner join Management m_brand
on mal_brand.ManagementID = m_brand.ManagementID
and m_brand.LevelID = @Insert_Management_Brand_Level_Here
inner join ManagementAccountLookup mal_region
on Account.AccountID = mal_region.AccountID
inner join Management m_region
on mal_region.ManagementID = m_region.ManagementID
and m_region.LevelID = @Insert_Management_Region_Level_Here
编辑:如果您需要显示所有帐户,您可以在括号中使用左/内连接组合:
select Account.AccountID,
m_brand.Name Brand,
m_region.Name Region
from Account
left join
(
ManagementAccountLookup mal_brand
inner join Management m_brand
on mal_brand.ManagementID = m_brand.ManagementID
and m_brand.LevelID = @Insert_Management_Brand_Level_Here
)
on Account.AccountID = mal_brand.AccountID
left join
(
ManagementAccountLookup mal_region
inner join Management m_region
on mal_region.ManagementID = m_region.ManagementID
and m_region.LevelID = @Insert_Management_Region_Level_Here
)
on Account.AccountID = mal_region.AccountID
为了使其更具可读性,您可以使用 CTE:
; with mal_level as (
select AccountID,
m.LevelID,
m.Name
from ManagementAccountLookup mal
inner join Management m
on mal.ManagementID = m.ManagementID
)
select Account.AccountID,
m_brand.Name Brand,
m_region.Name Region
from Account
left join mal_level m_brand
on Account.AccountID = m_brand.AccountID
and m_brand.LevelID = @Insert_Management_Brand_Level_Here
left join mal_level m_region
on Account.AccountID = m_region.AccountID
and m_region.LevelID = @Insert_Management_Region_Level_Here
或外部应用:
select Account.AccountID,
b.Brand,
r.Region
from Account
outer apply
(
select m_brand.Name Brand
from ManagementAccountLookup mal_brand
inner join Management m_brand
on mal_brand.ManagementID = m_brand.ManagementID
and m_brand.LevelID = @Insert_Management_Brand_Level_Here
where mal_brand.AccountID = Account.AccountID
) b
outer apply
(
select m_region.Name Region
from ManagementAccountLookup mal_region
inner join Management m_region
on mal_region.ManagementID = m_region.ManagementID
and m_region.LevelID = @Insert_Management_Region_Level_Here
where mal_region.AccountID = Account.AccountID
) r