简体   繁体   中英

Select rows as different columns in SQL Server

I have table with following structure:

在此处输入图片说明

I want to show it like this:

在此处输入图片说明

Maximum 5 users will be there per LocIC and AuditID

You want conditional aggregation:

select LocID, AuditID,
       max(case when Seq = 1 then userID end) User1,
       max(case when Seq = 2 then userID end) User2,
       max(case when Seq = 3 then userID end) User3,
       max(case when Seq = 4 then userID end) User4,   
       max(case when Seq = 5 then userID end) User5   
from (select *,
              row_number() over (partition by LocID, AuditID order by userID) Seq
      from table a 
     ) t
group by LocID, AuditID;

You can use group_concat feature SQL server.

select LocID,AuditID, group_concat(userID) listUser from table group by LocID, AuditID

Here later you can use listUser column values to show in table

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