如何将多条记录连接到SQL中的单个记录中?

时间:2014-08-13 06:22:08

标签: sql sql-server join

这是我的输入表:

ID    Position  Email  
1     1         email1  
1     2         email2  
1     3         email3  
2     1         emaila  
3     1         emailz  
3     2         emaily  

这是我要填写的输出表:

ID  primary_email Secondary_email    
1   email1        email2  
2   emaila  
3   emailz        emaily  

1 个答案:

答案 0 :(得分:0)

可能是这样的

SELECT ID,
       MAX(CASE WHEN Position = 1 THEN Email ELSE '' END) AS primary_email,
       MAX(CASE WHEN Position = 2 THEN Email ELSE '' END) AS Secondary_email
FROM YourTable
GROUP BY ID;