SQL Pivot with String

前端 未结 2 1583
面向向阳花
面向向阳花 2020-12-14 09:37

I have two tables in SQL Server: Customer and Address

Customer Table:

CustomerID  FirstName  LastName
----------- ---------- -------         


        
相关标签:
2条回答
  • I would write it like this instead:

    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'
    
    0 讨论(0)
  • 2020-12-14 10:22

    It is giving this row because you have AddressID in the select list for you subquery "P". So even though you don't have AddressID in you top level select this, the PIVOT function is still grouping by it. You need to change this to:

    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
    

    Although I would be inclined to use an explicit INNER JOIN rather than an implicit join between customer and Address.

    0 讨论(0)
提交回复
热议问题