How to pivot in SQL

前端 未结 3 1507
無奈伤痛
無奈伤痛 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条回答
  •  一个人的身影
    2021-01-07 11:51

    Have you read the documentation on PIVOT in Microsoft SQL Server 2005?

    SELECT CustId, 
      [1] AS Admin,
      [2] AS Manager,
      [3] AS Support,
      [4] AS Assistant
    FROM (SELECT c.CustId, r.RoleId
    FROM CustomerRoles c JOIN Roles r USING (RoleId)) AS s
    PIVOT (
     COUNT(CustId)
     FOR RoleId IN ([1], [2], [3], [4])
    ) AS pvt
    ORDER BY CustId;
    

    I haven't tested the above, but just based it on the doc. This may get you started.

    There doesn't seem to be a way to generate the columns dynamically. You have to hard-code them.

提交回复
热议问题