SQL Unpivot multiple columns Data

前端 未结 2 2057
温柔的废话
温柔的废话 2020-12-10 01:20

I am using SQL server 2008 and I am trying to unpivot the data. Here is the SQL code that I am using,

CREATE TABLE #pvt1 (VendorID int, Sa int, Emp1 int,Sa1          


        
2条回答
  •  甜味超标
    2020-12-10 02:11

    The answer by Taryn is indeed super useful, and I'd like to expand one aspect of it.

    If you have a very un-normalized table like this, with multiple sets of columns for e.g. 4 quarters or 12 months:

    +-------+------+------+------+------+------+------+-------+------+
    | cYear | foo1 | foo2 | foo3 | foo4 | bar1 | bar2 | bar3  | bar4 |
    +-------+------+------+------+------+------+------+-------+------+
    |  2020 |   42 |  888 |    0 |   33 | one  | two  | three | four |
    +-------+------+------+------+------+------+------+-------+------+
    

    Then the CROSS APPLY method is easy to write and understand, when you got the hang of it. For the numbered column, use constant values.

    SELECT 
        cYear,
        cQuarter,
        foo,
        bar
    FROM temp
    
    CROSS APPLY
    (
      VALUES
        (1, foo1, bar1),
        (2, foo2, bar2),
        (3, foo3, bar3),
        (4, foo4, bar4)
    
    ) c (cQuarter, foo, bar)
    

    Result:

    +-------+----------+-----+-------+
    | cYear | cQuarter | foo |  bar  |
    +-------+----------+-----+-------+
    |  2020 |        1 |  42 | one   |
    |  2020 |        2 | 888 | two   |
    |  2020 |        3 |   0 | three |
    |  2020 |        4 |  33 | four  |
    +-------+----------+-----+-------+
    

    SQL Fiddle

提交回复
热议问题