使用sql中的链接表选择数据

时间:2013-05-08 22:16:45

标签: sql tsql

我有链接表和表格。链接表将有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

区域始终以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.

1 个答案:

答案 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;

请参阅SQL Fiddle with Demo