Search code examples
sqlsql-serverunpivot

SQL server using unpivot function


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

Table structure

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

SQL fiddle link

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


Solution

  • 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 Fiddle

    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 Fiddle