T-SQL Group Rows Into Columns

前端 未结 2 1985
再見小時候
再見小時候 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条回答
  •  情书的邮戳
    2020-12-10 06:04

    You might pivot the table using row_number() as a source of column names:

    select *
    from
    (
      select ref, 
             name, 
             link,
             row_number() over (partition by ref, name order by link) rn
      from table1
    ) s
    pivot (min (link) for rn in ([1], [2], [3], [4])) pvt
    

    Simply extend the list of numbers if you have more rows.

    Live test is @ Sql Fiddle.

提交回复
热议问题