SQL Unpivot multiple columns Data

前端 未结 2 1933
温柔的废话
温柔的废话 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:05

    An easier way to unpivot the data would be to use a CROSS APPLY to unpivot the columns in pairs:

    select vendorid, orders, orders1
    from pvt1
    cross apply
    (
      select emp1, sa union all
      select emp2, sa1
    ) c (orders, orders1);
    

    See SQL Fiddle with Demo. Or you can use CROSS APPLY with the VALUES clause if you don't want to use the UNION ALL:

    select vendorid, orders, orders1
    from pvt1
    cross apply
    (
      values 
        (emp1, sa),
        (emp2, sa1)
    ) c (orders, orders1);
    

    See SQL Fiddle with Demo

提交回复
热议问题