Search code examples
sqlsql-serverpivot-tabletranspose

SQL Server transpose rows to column


We have this table:

Column A Column B
01-01-2020 23
01-01-2020 24
01-01-2020 25
02-01-2020 11
02-01-2020 15

The requirement is to load the data in single row based on datetime column.

Column A Column B Column C Column D
01-01-2020 23 24 25
02-01-2020 11 15

There can be up to 200 unique values against single datetime value.

How can this be achieved in a query?

I have tried using pivot but that results is aggregation which is not what I am after.


Solution

  • Since you have up to 200 hundred columns, I figured it would be best to number them. You can expand up to the required number of columns

    Example

    Select *
      From (
            Select [Column A]
                  ,[Column B]
                  ,RN  = row_number() over (partition by [Column A] order by [Column B] )
             From  YourTable
           ) src
     Pivot ( max([Column B]) for RN in ( [1], [2], [3], [4], [5], [6], [7], [8], [9],[10]
                                      ,[11],[12],[13],[14],[15],[16],[17],[18],[19],[20] 
                                      ,[21],[22],[23],[24],[25],[26],[27],[28],[29],[30] 
                                      ) ) Pvt