Join tables with rows

前端 未结 1 464
礼貌的吻别
礼貌的吻别 2020-12-21 12:52

I am trying to join three tables in SQL Server 2008 R2, where I want the items in the second table to be added as new column.

To explain in detail - I have 3 tables:

相关标签:
1条回答
  • 2020-12-21 13:19

    If you have only a few numbers of positions, you can do it with PIVOT keyword

    select
        UserID,
        UserName,
        [1] as Position1,
        [2] as Position2,
        [3] as Position3
    from
    (
        select
            U.UserID, U.UserName, P.PositionName,
            row_number() over (partition by 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)
            for P.RowNum in ([1], [2], [3])
        ) as PIV
    

    SQL FIDDLE

    If, however, you want to have a dynamic number of columns, you have to use dynamic SQL, like this

    declare @stmt nvarchar(max), @stmt_columns1 nvarchar(max), @stmt_columns2 nvarchar(max)
    declare @Temp_Data table (RowNum nvarchar(max))
    
    insert into @Temp_Data
    select distinct row_number() over (partition by 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
    
    select @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 (partition by 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)
            for P.RowNum in (' + @stmt_columns1 + ')
        ) as PIV'
    
    exec sp_executesql @stmt = @stmt
    

    SQL FIDDLE

    0 讨论(0)
提交回复
热议问题