2012-04-25 112 views
6

我在SQL Server中的兩個表:客戶和地址SQL樞軸與字符串

客戶表

CustomerID FirstName LastName 
----------- ---------- ---------- 
1   Andrew  Jackson   
2   George  Washington 

地址表

AddressID CustomerID AddressType City 
----------- ----------- ----------- ---------- 
1   1   Home  Waxhaw  
2   1   Office  Nashville  
3   2   Home  Philadelphia 

這是輸出我需要:

CustomerID Firstname HomeCity  OfficeCity 
----------- ---------- ---------- ---------- 
1   Andrew  Waxhaw  Nashville 
2   George  Philadelphia Null 

這是我的查詢,但沒有得到正確的結果:

SELECT CustomerID, Firstname, HOme as HomeCity, Office as OfficeCity FROM 
    (SELECT C.CustomerID, C.FirstName, A.AddressID, A.AddressType, A.City 
    FROM Customer C, Address A 
    WHERE C.CustomerID = A.CustomerID)as P 
PIVOT (MAX(city) FOR AddressType in ([Home],[Office])) as PVT 

這是我得到的結果是:

CustomerID Firstname HomeCity  OfficeCity 
----------- ---------- ---------- ---------- 
1   Andrew  Waxhaw  NULL 
1   Andrew  NULL   Nashville 
2   George  Philadelphia Null 

正如你可以看到客戶1示出了兩次了最終的結果。每個客戶只能得到一行嗎?

我擡頭一看這個例子,但是沒有幫助:HTTP://stackoverflow.com/questions/6267660/sql-query-to-convert-rows-into-columns

感謝

回答

11

這是給此行,因爲你有AddressID在選擇列表中你子查詢「P」。所以即使你沒有AddressID在你的頂層選擇這個,PIVOT函數仍然是按它分組的。您需要將此更改爲:

SELECT CustomerID, Firstname, Home as HomeCity, Office as OfficeCity 
FROM ( SELECT C.CustomerID, C.FirstName, A.AddressType, A.City 
      FROM #Customer C, #Address A 
      WHERE C.CustomerID = A.CustomerID 
     ) AS P 
     PIVOT 
     ( MAX(city) 
      FOR AddressType in ([Home],[Office]) 
     ) AS PVT 

雖然我會傾向於使用明確的INNER JOIN而不是一個隱含的客戶和地址之間的連接。

+0

太棒了,工作!謝謝!!我沒有意識到addressID導致它。我已經習慣了隱式連接,但是我會像上面提到的那樣開始使用INNER JOIN。 – kthiagar 2012-04-25 16:26:14

+1

在這種情況下,它是不是使用隱式或內部聯接有很大的區別,並且有關於主題的許多不同的討論,例如[here](http://stackoverflow.com/questions/44917/explicit -vs隱-SQL聯接)。我個人認爲,顯式連接更容易閱讀,允許在'INNER'和'OUTER'連接之間更輕鬆地進行更改,還可以通過丟失where子句來減少意外交叉連接的可能性。 – GarethD 2012-04-25 16:31:49

6

我會寫這樣的而不是:

SELECT C.CustomerID, C.Firstname, 
    Home.City as HomeCity, 
    Office.City as OfficeCity 
FROM Customer C 
    LEFT JOIN Address Home 
     on Home.CustomerID = C.CustomerID and Home.AddressType = 'Home' 
    LEFT JOIN Address Office 
     on Office.CustomerID = C.CustomerID and Office.AddressType = 'Office' 
+1

謝謝,這看起來是另一種不使用PIVOT的好方法。 – kthiagar 2012-04-25 16:29:19