SQL Server中基于ID的一列到多列

时间:2017-10-26 16:30:15

标签: mysql sql sql-server

我有一个表结构:

ID |类型|值
1电子邮件abcd@xyz.com
1电话12345
2电话56789
2 WorkPhone 546789

我想将其转换为

ID |电子邮件|电话|工作电话
1 abcd@xyz.com 12345无 2 Null 56789 546789

任何人都可以帮我解决它。对不起,如果之前已经重复过这个问题。

2 个答案:

答案 0 :(得分:5)

使用条件聚合:

select 
    id
  , max(case when type = 'email' then value end) as email
  , max(case when type = 'phone' then value end) as phone
  , max(case when type = 'workphone' then value end) as workphone
from t
group by id

pivot()(在sql-server中):

select id, email, phone, workphone
from t
pivot (max(value) for type in ([email],[phone],[workphone])) p

rextester演示:http://rextester.com/UGT52844

都返回:

+----+--------------+-------+-----------+
| id |    email     | phone | workphone |
+----+--------------+-------+-----------+
|  1 | abcd@xyz.com | 12345 | NULL      |
|  2 | NULL         | 56789 | 546789    |
+----+--------------+-------+-----------+

答案 1 :(得分:1)

上述解决方案的替代方案是SQL Server中的Pivot命令。以下答案仅适用于SQL-Server。此语法不适用于MYSQL。您已使用这两个标记标记了此问题,因此我不确定您正在运行哪个。如果您使用的是MSSQL,则以下链接将深入介绍该命令 https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot

以下代码将实现您正在寻找的结果:

   SELECT [ID] AS [ID],
       [Email] AS Email, 
       [Phone] AS Phone,
       [WorkPhone] AS WorkPhone
   FROM 
   (
        SELECT ID, 
               [TYPE], 
               [Value] 
        FROM dbo.Pivot_Ex
   ) AS FT
   PIVOT 
   (
        MAX([Value])
        FOR FT.TYPE IN ([Email], [Phone], WorkPhone)
   ) AS PivotTable1