我试图使用PIVOT将行转换为列。我只有数字示例,但我需要使用varchar进行PIVOT

时间:2017-07-08 13:37:54

标签: sql

需要转换以下内容

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

1 个答案:

答案 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     |           |
+---------+-----------+-----------+-----------+