T-SQL Group Rows Into Columns

前端 未结 2 1984
再見小時候
再見小時候 2020-12-10 05:32

How can I group an (unknown) number of rows into a single row where the set columns determine the grouping?

For example, shift

Ref      Name                  


        
2条回答
  •  旧时难觅i
    2020-12-10 06:11

    If the number of different Links is unkown this needs to be done dynamically. I think this will work as required:

    DECLARE @SQL NVARCHAR(MAX) = ''
    SELECT  @SQL = @SQL + ',' + QUOTENAME(Rownumber)
    FROM    (   SELECT  DISTINCT ROW_NUMBER() OVER(PARTITION BY Ref, Name ORDER BY Link) [RowNumber]
                FROM    yourTable
            ) d
    
    SET @SQL = 'SELECT  *
                FROM    (   SELECT  Ref, 
                                    name, 
                                    Link, 
                                    ROW_NUMBER() OVER(PARTITION BY Ref, Name ORDER BY Link) [RowNumber]
                            FROM    yourTable
                        ) data
                        PIVOT
                        (   MAX(Link)
                            FOR RowNumber IN (' + STUFF(@SQL, 1, 1, '') + ')
                        ) pvt'
    
    EXECUTE SP_EXECUTESQL @SQL
    

    It is a slight varation of the usual PIVOT function because normally link would be in the column header. It basically determines the number of columns required (i.e. the maximum distinct values for Link per ref/Name) then Pivots the values into these columns.

提交回复
热议问题