Skip to content
Advertisement

How to pivot two columns in SQL Server?

I have the following table

 UserName   UserId   
    -----      ----    
    Bob         445       
    Bob         450       
    Rachel      512       
    Rachel      520       
    Rachel      570       
    Simon       771       
    Simon       760 

and I am trying to pivot it so that a new column is created for each username, with UserID’s listed per UserName

Bob       Rachel       Simon
445          512        771
450          520        760
             570

Advertisement

Answer

Just in case you were looking for a dynamic pivot

Example

Declare @SQL varchar(max) = '
Select *
From (
        Select * 
              ,RN = row_number() over (partition by username order by UserId) 
        from #YourTable
     ) A
 Pivot (max(UserID) For [UserName] in (' + stuff((Select distinct ',' + QuoteName([UserName]) From  #YourTable Order By 1 For XML Path('')),1,1,'')  + ') ) p
'

--Print @SQL
Exec(@SQL);

Returns

RN  Bob   Rachel    Simon
1   445   512       760
2   450   520       771
3   NULL  570       NULL
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement