如何在SQL Server中将行转换为列?

时间:2017-11-02 14:44:40

标签: sql sql-server

enter image description here

如何使用SQL Server实现此目的?

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:-1)

您需要使用PIVOT。 关于Stack Overflow

的大量例子

在OP中复制预期的答案

DECLARE @tab TABLE (ID INT, CODE INT, ECODE VARCHAR(10))
INSERT INTO @tab
(ID, CODE, ECODE)
VALUES
(1, 101, 'error1'),
(1, 102, 'error2'),
(1, 103, 'error3'),
(1, 104, 'success'),
(2, 101, 'error1'),
(2, 102, 'error2'),
(2, 103, 'error3'),
(2, 104, 'success')


SELECT
      T.ID
    , MAX(CASE WHEN T.CODE = 101 THEN T.CODE END) 'CODE1'
    , MAX(CASE WHEN T.ECODE = 'error1' THEN T.ECODE END) 'ECODE1'
    , MAX(CASE WHEN T.CODE = 102 THEN T.CODE END) 'CODE2'
    , MAX(CASE WHEN T.ECODE = 'error2' THEN T.ECODE END) 'ECODE2'
    , MAX(CASE WHEN T.CODE = 103 THEN T.CODE END) 'CODE3'
    , MAX(CASE WHEN T.ECODE = 'error3' THEN T.ECODE END) 'ECODE3'
    , MAX(CASE WHEN T.CODE = 104 THEN T.CODE END) 'CODE4'
    , MAX(CASE WHEN T.ECODE = 'Success' THEN T.ECODE END) 'ECODE4'
FROM @tab T
GROUP BY T.ID