2014-12-03 54 views
0

在SQL Server 2012中,我有一個看起來像四個表:拼合SQL 4個表

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 | 

注意的第二個問題沒有一個房(無位置爲必填項),位置少的問題是有效的。請注意,其他約束可能導致所需的位置,但我認爲這與此問題無關。

+2

向我們展示你的嘗試和努力,到目前爲止 - 並告訴我們你就完蛋了! – 2014-12-03 17:26:07

+0

我想你在'IssueLocations'表中缺少'TypeID'。 – 2014-12-03 17:27:25

+0

@ Dave.Gugg問題 - > IssueLocations - >位置 - >位置類型 – brykneval 2014-12-03 17:29:44

回答

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 
+0

可能會有更多或更少的位置類型。沒有列的硬編碼。 – 2014-12-03 19:12:32