SQL 服务器如何将列值转换为行

SQL server how to convert column values into rows

我会尽力解释我的问题。

我的table结构:

name Code_1 Code_1_value Code_2 Code_2_value Code_3 Code_3_value
N1    ABC1        10      ABC2       15       ABC3        6
N2    ABC1        3       NULL      NULL      BAA1        10
N3    ABC4        5       ABC2       11       ADC3        6

我想将此值转换为新格式:

name    code    value
N1      ABC1      10
N1      ABC2      15
N1      ABC3      6
N2      ABC1      3

我不知道逻辑上应该如何(枢轴?)

查询-

DECLARE @t TABLE (
    name VARCHAR(50) PRIMARY KEY,
    Code_1 VARCHAR(50),
    Code_1_value INT,
    Code_2 VARCHAR(50),
    Code_2_value INT,
    Code_3 VARCHAR(50),
    Code_3_value INT
)
INSERT INTO @t
VALUES
    ('N1', 'ABC1', 10, 'ABC2', 15  , 'ABC3', 6),
    ('N2', 'ABC1', 3 , NULL,   NULL, 'BAA1', 10),
    ('N3', 'ABC4', 5 , 'ABC2', 11  , 'ADC3', 6)

SELECT name, code, value
FROM @t
CROSS APPLY (
    VALUES (Code_1, Code_1_value), (Code_2, Code_2_value),  (Code_3, Code_3_value)
) t2 (code, value)
WHERE code IS NOT NULL

输出-

name     code     value
-------- -------- -----------
N1       ABC1     10
N1       ABC2     15
N1       ABC3     6
N2       ABC1     3
N2       BAA1     10
N3       ABC4     5
N3       ABC2     11
N3       ADC3     6

Post 关于 UNPIVOT -

http://blog.devart.com/is-unpivot-the-best-way-for-converting-columns-into-rows.html

这也可以用 UNION

SELECT name,code_1 as code,code_1_value as value from yourTable
UNION ALL
SELECT name,code_2 as code,code_2_value as value from yourTable
UNION ALL    
SELECT name,code_3 as code,code_3_value as value from yourTable