SQL Server如何将列值转换为行

时间:2016-01-28 08:26:25

标签: sql sql-server database tsql unpivot

我会尝试解释我的问题。

我的表结构:

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

我不知道逻辑应该如何(转角?)

2 个答案:

答案 0 :(得分:5)

查询 -

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

发布约UNPIVOT -

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

答案 1 :(得分:2)

这也可以通过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