2017-12-27 421 views
2

我有以下值,我試圖將其轉換成一行。試圖基於另一個數據透視一列

---------------------------------------------- 
EmplID | SSN  |  source |Code | 
1234 | 111-11-1111 | L   | AB123 | 
1234 | 111-11-1111 | E   | ZY987 | 
9876 | 222-22-2222 | L   | CD456 | 
9876 | 222-22-2222 | E   | XW789 | 
---------------------------------------------- 

我想要的輸出是這樣的:

------------------------------------------------ 
Empl_ID | ssn  | LCode  | ECode | 
1234  | 111-11-1111| AB123  | ZY987 | 
9876  | 222-22-2222| CD456  | XW789 | 

任何想法?

對不起,如果上面的格式看起來不可靠

謝謝!

回答

2

你可以做到這一點直截了當如下

SELECT Empl_ID, 
     ssn, 
     MAX(CASE WHEN source = 'L' THEN Code END) AS LCode, 
     MAX(CASE WHEN source = 'E' THEN Code END) AS ECode 
FROM YourTable 
GROUP BY Empl_ID, 
      ssn 

或者使用PIVOT

SELECT EmplID, 
     SSN, 
     L AS LCode, 
     E AS ECode 
FROM (SELECT EmplID, 
       SSN, 
       source, 
       Code 
     FROM YourTable) AS PS /*So still works as desired if other columns added*/ 
PIVOT (MAX(Code) FOR source IN (L, E)) P 
相關問題