1行の情報を取得するには、ManagementAccountLookup/Managementの組み合わせを2回追加する必要があります。LevelID
必要に応じて左結合への移行を容易にするために、直接結合に基準を設定しました。
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