尝试根据另一列中的值来旋转一列

时间:2017-12-27 19:06:13

标签: sql-server

我有以下值,我正试图转入一行。

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

有什么想法吗?

很抱歉,如果上面的格式看起来很糟糕

谢谢!

1 个答案:

答案 0 :(得分: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