SQL Server - 根据'type-column'将列转换为行

时间:2016-09-30 10:48:43

标签: sql sql-server

我有以下表格:

ID | Type | Info
1  | Cell | 00123456789
1  | Mail | id1@hotmail.com
1  | Tel  | 0123456
2  | Mail | id2@mail.com
.. | ..   | ..

我想要以下结果:

ID | Cell        | Mail            | Tel  
1  | 00123456789 | id1@hotmail.com | 0123456
2  | NULL        | id2@mail.com    | NULL  

我尝试使用cte并在ID上加入它们,但这对于(例如)Cell编号为空的行没有帮助。有什么想法吗?

根据要求:我使用的代码(我编辑了这个,因为它在我自己的数据库中要大得多)

WITH cte_cell
AS
(
    SELECT ID, TYPE,  INFO AS cell
    FROM   table1
    WHERE  (TYPE = 'cell')
),

cte_mail
AS
(
    SELECT ID, TYPE,  INFO AS mail
    FROM table1
    WHERE TYPE = 'mail'
),

cte_tel
AS
(
    SELECT ID, TYPE, INFO AS tel
    FROM table1
    WHERE TYPE = 'tel'
)

SELECT  cte_cell.ID AS cte_cell_ID, 
        cte_mail.ID AS cte_mail_ID, 
        cte_tel.ID AS cte_tel_ID, 

        cte_cell.cell, 
        cte_mail.mail, 
        cte_tel.tel

FROM cte_cell FULL JOIN cte_mail
    ON cte_cell.ID = cte_mail.ID
FULL JOIN cte_tel
    ON cte_mail.ID = cte_tel.ID
;

2 个答案:

答案 0 :(得分:1)

如果您提到的type列中的值有限,请参阅。然后,您可以使用CASE表达式。否则你可以使用动态sql查询。

<强>查询

SELECT ID, 
MAX(CASE [Type] WHEN 'Cell' THEN [info] END) AS [Cell],
MAX(CASE [Type] WHEN 'Mail' THEN [info] END) AS [Mail],
MAX(CASE [Type] WHEN 'Tel' THEN [info] END) AS [Tel]
FROM [your_table_name]
GROUP BY ID;

通过使用动态SQL查询。

<强>查询

DECLARE @sql AS varchar(max);

SELECT @sql = 'SELECT ID, ' + STUFF((SELECT
     ', MAX(CASE [Type] WHEN ''' + [Type] + ''' THEN [info] END) AS ' + [Type]
     FROM [your_table_name]
FOR xml PATH (''))
    , 1, 2, '') + ' FROM [your_table_name] GROUP BY [ID];';

EXEC (@sql);

答案 1 :(得分:1)

使用PIVOT:如果您有多于三种类型,并且没有更好地定义动态数据透视查询

SELECT Id,  [Cell],[Mail],[Tel] from 
(
    SELECT *
    FROM TableName
) x
pivot 
(
    MAX(Info)
    FOR Type in ([Cell],[Mail],[Tel])
) p

<强>输出:

enter image description here