简体   繁体   中英

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

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

This is tricky. You can use aggregation, but you need to number the rows:

select max(case when username = 'Bob' then uid end) as bob,
       max(case when username = 'Rachel' then uid end) as Rachel,
       max(case when username = 'Simon' then uid end) as Simon      
from (select t.*,
             row_number() over (partition by username order by uid) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

Note: This orders the values by uid , which is slightly different from your result set. SQL tables represent unordered sets. There is no ordering of the original rows, unless a column specifies that ordering. If you have such a column, you can use that instead of order by uid for row_number() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM