我有三个表:Account
,Management
和ManagementAccountLookup
。
帐户表包含位置。 Management表包含业务层次结构中每个级别的记录。 Management表还包含一个值( LevelID),它指示记录所在层次结构中的哪个级别.ManagementAccountLookup表是连接它们的查找表。
我在编写查询时遇到问题,无法通过两个相关的管理记录获取所有帐户。
例如:一个帐户可能有5个或更多与之关联的管理记录,但我只关心具有品牌或地区级别ID的两个特定管理。此外,我只希望帐户在结果网格中显示一次。
结果集应如下所示:
AccountID Brand Region
--------- -------- ------
account1 Wendys East US
account2 McDonalds West US
这似乎是一个简单的问题,但我无法弄清楚如何获得该结果。我已经尝试过自联接,子查询以及我能想到的其他所有内容,但我似乎无法将结果整合到一行中。
任何帮助都将不胜感激。
*编辑: ManagementAccountLookup有两个字段(AccountID,ManagementID)。这是其他两个表格的PK 管理层有一个LevelID列,可以告诉您该记录是品牌,地区,区等...
“品牌和区域”将是“管理”表格中的两个单独行。我需要结果网格将它们放在同一行。
答案 0 :(得分:2)
您需要两次添加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
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