sql server - Query to transform unknown number of rows to unknown number of columns -
i'm been looking hours @ different options (pivot, cross join etc...) transform unknown number of rows unknown number of columns sql server 2008 , i'm more lost before started.
basically 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 build query or sp transform result of left join nice "pivot" table 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 help!
big thank aaron putting me on right track!
alter procedure dbo.roleactionspivot set nocount on declare @cols nvarchar(max), @query nvarchar(max); select action.actionid, action.actionname , role.roleid, role.rolename #tmproleaction action left join roleactions on action.actionid = roleaction.actionid left join role on roleaction.roleid = role.roleid set @cols = stuff((select distinct ',' + quotename(rolename) #tmproleaction xml path(''), type ).value('.', 'nvarchar(max)') ,1,1,'') set @query = 'select actionid, actionname, ' + @cols + ' (select * #tmproleaction) x pivot ( max(roleid) rolename in (' + @cols + ')) p ' execute(@query)
Comments
Post a Comment