您需要添加ManagementAccountLookup/Management組合兩次以獲取一行信息。我已經將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
或者outer apply:
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
也許你可以向我們展示表的模式。我們想要幫助你,但是我們不知道要加入什麼領域 –
對不起,我應該這樣做,我只是不想讓我的問題更加混亂,因爲增加了一些不必要的數據。我做了一個編輯,使它更容易理解表結構。感謝您的意見,我會牢記未來的問題。 – Justin