1

I'm been looking for hours at different options (PIVOT, CROSS JOIN etc...) to transform an unknown number of rows to an unknown number of columns with SQL server 2008 and I'm even more lost than before I started.

Basically I have 3 tables:

Role

|id| name|
| 1|role1|
| 2|role2|
| 3|role3|

Action

|id|  name |
| 1|action1|
| 2|action2|
| 3|action3|

RoleAction

|roleId| actionId|
|   1  |    1    |
|   1  |    2    |
|   2  |    1    |
|   3  |    2    |

Is there anyway to build a query or SP that would transform the result of a LEFT JOIN to a nice "pivot" table like this:

|actionId|actionName|role1|role2|role3|.....|role n|
|   1    | action1  |  1  |  1  |  0  |.....|   0  |
|   2    | action2  |  1  |  0  |  1  |.....|   0  |
|   3    | action3  |  0  |  0  |  0  |.....|   0  |
|   .    |    .     |  .  |  .  |  .  |.....|   .  |
|   .    |    .     |  .  |  .  |  .  |.....|   .  |
|   n    | action n |  0  |  0  |  0  |.....|   0  |

Many many thanks for your help!

4

1 回答 1

1

非常感谢 Aaron 让我走上正轨!

ALTER PROCEDURE dbo.RoleActionsPivot
AS

SET NOCOUNT ON

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX);

SELECT  Action.ActionId, Action.ActionName , Role.RoleId, Role.RoleName
INTO    #tmpRoleAction
FROM    Action LEFT JOIN RoleActions ON Action.ActionId = RoleAction.ActionId 
    LEFT JOIN Role ON RoleAction.RoleId = Role.RoleId

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(RoleName) 
            FROM #tmpRoleAction
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ActionId, ActionName, ' + @cols + ' FROM

    (SELECT * FROM #tmpRoleAction) x

    PIVOT  ( max(RoleId) for RoleName in (' + @cols + ')) p '


execute(@query)
于 2012-06-04T17:31:52.207 回答