16

我在 SQL Server 中有两个表:客户和地址

客户表

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

谢谢

4

2 回答 2

22

它给出了这一行,因为您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在客户和地址之间使用显式而不是隐式连接。

于 2012-04-25T16:22:31.797 回答
12

我会这样写:

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'
于 2012-04-25T16:19:01.510 回答