How to pivot in SQL

前端 未结 3 1498
無奈伤痛
無奈伤痛 2021-01-07 11:12

I am not sure if this would be called pivoting.

Data in my SQL 2005 table [CustromerRoles] is as such:

CustId  RoleId
2        4
2           


        
3条回答
  •  梦毁少年i
    2021-01-07 11:49

    Try this:

    SELECT 
        CustId, 
        SUM(ISNULL(Admin,0)) AS Admin, 
        SUM(ISNULL(Manager,0)) AS Manager, 
        SUM(ISNULL(Support,0)) AS Support, 
        SUM(ISNULL(Assistant,0)) AS Assistant
    FROM
    (
        SELECT cr.CustId, cr.RoleId, Role, 1 AS a
        FROM CustromerRoles cr
        INNER JOIN Roles r ON cr.RoleId = r.RoleId
    ) up
    PIVOT (MAX(a) FOR Role IN (Admin, Manager, Support, Assistant)) AS pvt
    GROUP BY CustId
    

    Tested. It gives the same result you want.

提交回复
热议问题