我有链接表和表格。链接表将有2个数据记录,一个是“Region”,另一个是“Sub-Region”,实际表也有2个“Region”和“Sub-Region”记录。我希望使用链接
获取单个记录我认为例子会解释更多我正在寻找的东西
EventID | RegionID | RegionType_Code
1 1 SSam
1 2 SRUSA
RegionID | RegionType_Code | Region_Name
1 SSam Americas
2 SRUSA USA
EventID| Region | Sub-Region
1 Americas USA
区域始终以SS
开始,子区域以SR
如何以这种方式获得输出?
这里有什么问题?
SELECT e.EventId,
e.Event_Code AS Code,
e.Event_Type_Description AS [Event],
e.Event_Name as Name,
max(case when left(er.RegionType_Code, 2) = 'SS' then r.region_name end) Region,
max(case when left(er.RegionType_Code, 2) = 'SR' then r.region_name end) SubRegion
FROM dbo.Event e
INNER JOIN Event_Region er ON er.EventId = e.EventId
INNER JOIN Region r ON r.RegionId = er.RegionId
group by e.EventId;
我收到错误
Column 'dbo.Event.Event_Code' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
答案 0 :(得分:4)
您应该能够使用CASE
的聚合函数:
select er.eventid,
max(case when left(er.RegionType_Code, 2) = 'SS' then r.region_name end) Region,
max(case when left(er.RegionType_Code, 2) = 'SR' then r.region_name end) SubRegion
from Event_Region er
inner join Region r
on er.regionid = r.regionid
group by er.eventid;