展平4个表的SQL

时间:2014-12-03 17:21:24

标签: sql-server sql-server-2012

在SQL Server 2012中,我有四个表格如下:

Issues

IssueID | IssueTitle
1       | Light Bulb Burnt Out
2       | Thermostat not working

LocationTypes

TypeID | Type
1        | Building
2        | Floor
3        | Room

Locations

 LocaltionID | TypeID    | Location      | ParentLocation
 0           |  1        | default       | 0 
 1           |  1        | Sears Tower   | 0 
 2           |  1        | IDS           | 0
 3           |  2        | Floor 1       | 1
 4           |  2        | Floor 2       | 1
 5           |  2        | Floor 3       | 1
 6           |  2        | Floor 4       | 1
 7           |  2        | Floor 5       | 1
 8           |  2        | Floor 6       | 1
 9           |  2        | Floor 7       | 1
 10          |  2        | Floor 8       | 1
 108         |  3        | Room 101      | 3
 109         |  3        | Room 102      | 3
 110         |  3        | Room 110      | 3
 111         |  3        | Room 202      | 4
 112         |  3        | Room 300      | 5
 175         |  2        | 1st Floor     | 2
 185         |  2        | 2nd Floor     | 2
 186         |  3        | Suite 295     | 185

IssueLocations

IssueID | LocationId 
1       | 1        
1       | 5        
1       | 112   
2       | 2
2       | 185

我想要做的是组合表格,以便每个发行者最终得到一行,字段名称为列标题和字段值,所以我最终得到:

结果:

IssueID  | IssueTitle             | Building     | Floor     | Room
--------------------------------------------------------------------------
1        | Light Bulb Burnt Out   | Sears Tower  | Floor 1   | Room 300 
2        | Thermostat not working | IDS          | 2nd Floor | 

注意第二个问题没有房间(不需要位置),位置较少的问题是有效的。请注意,其他约束可能会导致所需的位置,但我认为这与此问题无关。

1 个答案:

答案 0 :(得分:2)

您需要使用Pivot 将您的行转置到列。

SQL FIDDLE DEMO

SELECT *
FROM  (SELECT il.IssueID,
              l.Location,
              i.IssueTitle,
              lt.Type
       FROM   Locations l
              JOIN LocationTypes lt
                ON l.TypeID = lt.TypeID
              JOIN IssueLocations il
                ON il.LocationId = l.LocaltionID
              JOIN issues i
                ON i.IssueID = il.IssueID) a
      PIVOT (Max(location)
            FOR type IN([Building],
                        [Floor],
                        [Room]))piv