需要转换以下内容
Country , code , result
('IND','AC1','Completed'),
('IND','AC2','Completed'),
('IND','AC3','Completed'),
('SL','AC1','Status'),
('SL','AC2','ERROR'),
('AUS','AC3','Completed')
到
Country , ac1 , ac2 , ac3
------------------------
ind , Completed , Completed , Completed
sl, Status ,Error
AUS, , ,Completed
答案 0 :(得分:1)
使用条件聚合:
select
Country
, max(case when code = 'AC1' then result else '' end) as AC1
, max(case when code = 'AC2' then result else '' end) as AC2
, max(case when code = 'AC3' then result else '' end) as AC3
from countries
group by Country
在SQL Server中使用pivot()
:
select
Country
, coalesce(AC1,'') as AC1
, coalesce(AC2,'') as AC2
, coalesce(AC3,'') as AC3
from countries
pivot (max(result) for code in (AC1,AC2,AC3)) p
rextester演示:http://rextester.com/ZTLYWY22412
返回(两者):
+---------+-----------+-----------+-----------+
| Country | AC1 | AC2 | AC3 |
+---------+-----------+-----------+-----------+
| AUS | | | Completed |
| IND | Completed | Completed | Completed |
| SL | Status | ERROR | |
+---------+-----------+-----------+-----------+