SQL server 使用 unpivot 函数

2021-09-14 00:00:00 sql sql-server unpivot

您将如何使用 SQL 获得以下输出?

How would you obtain the following output using SQL?

 Type:  Value  Type2       Value2
    p_01    1     ofpk_01     1
    p_02    2     ofpk_02     2
    p_03    3     ofpk_03     3

表结构

 create table test(p_01     int,
                   p_02     int,
                   p_03     int,
                   ofpk_01  int,
                   ofpk_02  int,
                   ofpk_03  int)

SQL 小提琴链接

这是否可以使用 unpivot 功能?这是我到目前为止所得到的:

Is this possible with unpivot function? here is what I've got so far:

推荐答案

另一种解决方案是使用CROSS APPLY:

Another solution is to use CROSS APPLY:

SELECT  ca.*
FROM    dbo.Test x
CROSS APPLY
(
    SELECT 'p_01' AS Type1, x.p_01 AS Value1, 'ofpk_01' AS Type2, x.ofpk_01 AS Value2 UNION ALL
    SELECT 'p_02' AS Type1, x.p_02 AS Value1, 'ofpk_02' AS Type2, x.ofpk_02 AS Value2 UNION ALL
    SELECT 'p_03' AS Type1, x.p_03 AS Value1, 'ofpk_03' AS Type2, x.ofpk_03 AS Value2
) ca;

SQL 小提琴

或者如果 2008+ 可以缩短为

Or if 2008+ this can be shortened to

SELECT  ca.*
FROM    dbo.Test x
CROSS APPLY
(VALUES

    ('p_01', x.p_01, 'ofpk_01', x.ofpk_01),
    ('p_02', x.p_02, 'ofpk_02', x.ofpk_02),
    ('p_03', x.p_03, 'ofpk_03', x.ofpk_03)
) ca(Type1, Value1, Type2, Value2);

SQL 小提琴

相关文章