2017-07-08 19 views
1

樞需要轉換以下我想使用PIVOT將行轉換爲列。我只有數字的例子,但我需要用VARCHAR

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

格式化你的問題,它傷害了我的眼睛,我不能讀它 – OverCoder

+0

我刪除了不兼容的SQL代碼。但基本的想法是,你可以使用'MAX()'而不是'SUM()'來代替你爲數字工作的任何代碼。 –

回答

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 

使用pivot()在SQL服務器:

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  |   | 
+---------+-----------+-----------+-----------+ 
+0

非常感謝你:)對於未格式化的問題抱歉。我下次會照顧它 –

+0

@KarthikCM樂意幫忙! – SqlZim

相關問題