ポジション数が少ない場合は PIVOT
でできます キーワード
select UserID, UserName, [1] as Position1, [2] as Position2, [3] as Position3from( select U.UserID, U.UserName, P.PositionName, row_number() over (U で区切る) .UserID order by P.PositionName) as RowNum from Positions_Users as PU inner join Positions as P on P.PositionID =PU.PositionID inner join Users as U on U.UserID =PU.UserID) as P pivot ( min(P.PositionName) ) ([1], [2], [3]) 内の P.RowNum を PIV として
プレ>ただし、動的な数の列が必要な場合は、次のように動的 SQL を使用する必要があります
declare @stmt nvarchar(max), @stmt_columns1 nvarchar(max), @stmt_columns2 nvarchar(max)declare @Temp_Data テーブル (RowNum nvarchar(max))insert into @Temp_Dataselect 個別の row_number() over (partition by U.UserID order by P.PositionName) as RowNumfrom Positions_Users as PU inner join Positions as P on P.PositionID =PU.PositionID inner join Users as U on U.UserID =PU.UserIDselect @stmt_columns1 =stuff((select ', [ ' + RowNum + ']' from @Temp_Data for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '')select @stmt_columns2 =stuff((select ', [' + RowNum + '] as Position' + RowNum from @Temp_Data for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '')select @stmt ='select UserID, UserName,' + @stmt_columns2 + 'from( select U.UserID, U.UserName, P.PositionName, row_number() over (P.PositionName による U.UserID 順のパーティション) as RowNum from Positions_Users P.PositionID =PU.PositionID 上の P としての PU 内部結合位置として内部結合 User as U on U.UserID =PU.UserID) as P ピボット ( min(P.PositionName) for P.RowNum in (' + @stmt_columns1 + ') ) as PIV'exec sp_executesql @stmt =@stmtコード> プレ>