试图基于另一个数据透视一列

我有以下值,我试图将其转换成一行。试图基于另一个数据透视一列

---------------------------------------------- 

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 |


任何想法?

对不起,如果上面的格式看起来不可靠

谢谢!

回答:

你可以做到这一点直截了当如下

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

以上是 试图基于另一个数据透视一列 的全部内容, 来源链接: utcz.com/qa/267050.html

回到顶部