0

我有链接表和表。链接表将有 2 条数据记录,一条是“Region”,另一条是“Sub-Region”,实际表也有 2 条“Region”和“Sub-Region”记录。我想使用链接作为单条记录

我认为示例将更多地解释我在寻找什么

Event_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

Region 总是以SSSub-Region 开头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.

4

1 回答 1

4

您应该能够使用带有 a 的聚合函数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;

请参阅带有演示的 SQL Fiddle

于 2013-05-08T22:24:05.487 回答