SQL Server - Rows to Columns without Aggregation

前端 未结 1 1322
挽巷
挽巷 2021-01-07 02:18

I have data that looks like this:

address      | id  
12AnyStreet  | 1234  
12AnyStreet  | 1235  
12AnyStreet  | 1236  
12AnyStreet  | 1237 
相关标签:
1条回答
  • 2021-01-07 02:50

    You can transform this data using the PIVOT function in SQL Server. In order to PIVOT the data, you will want to create your new column using the row_number().

    If you have a known number of values, then you can hard-code the query:

    select *
    from
    (
      select address, id,
        'id_'+cast(row_number() over(partition by address 
                                    order by id) as varchar(20)) rn
      from yourtable
    ) src
    pivot
    (
      max(id)
      for rn in ([id_1], [id_2], [id_3], [id_4])
    ) piv
    

    See SQL Fiddle with Demo

    But if the values are unknown then you will need to use dynamic SQL:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT distinct ',' 
                          + QUOTENAME(rn) 
                        from
                        (
                          select 'id_'+cast(row_number() over(partition by address 
                                    order by id) as varchar(20)) rn
                          from yourtable
                        ) src
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT address,' + @cols + ' from 
                 (
                    select address, id,
                      ''id_''+cast(row_number() over(partition by address 
                                                  order by id) as varchar(20)) rn
                    from yourtable
                ) x
                pivot 
                (
                    max(id)
                    for rn in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    See SQL Fiddle with Demo

    The result of both queries is:

    |     ADDRESS | ID_1 | ID_2 | ID_3 | ID_4 |
    -------------------------------------------
    | 12AnyStreet | 1234 | 1235 | 1236 | 1237 |
    
    0 讨论(0)
提交回复
热议问题