将多列移动到行,将一行移动为列

时间:2016-08-05 19:03:00

标签: sql-server sql-server-2012 sql-server-2008-r2

我的查询结果在临时表中,如下所示:

CREATE TABLE #temptable
(
productid INT,
date  DATE,
Indicator varchar(max),
VendorCode INT,
 morning INT,
 noon INT,
 evening INT
)



insert into #temptable values (101,'8-5-2016', 'High', 202, 0,1,0)
insert into #temptable values (101,'8-6-2016', 'High', 202, 0,0,1)
insert into #temptable values (101,'8-5-2016', 'Low', 202, 0,0,1)
insert into #temptable values (101,'8-6-2016', 'Low', 202, 0,0,1)
insert into #temptable values (101,'8-5-2016', 'Avg', 202, 1,0,1)
insert into #temptable values (101,'8-6-2016', 'Avg', 202, 0,0,1)



select * from #temptable

我需要输出看起来像这样:

enter image description here

我看过使用枢轴,但看起来只适用于聚合?有一个简单的方法吗?

2 个答案:

答案 0 :(得分:1)

首先应用unpivot运算符,然后pivot结果,您可以获得所需的结果:

select 
    productid, VendorCode, date, time, Low, High, Avg
from (
    select productid, VendorCode, date, time, Indicator, val
    from #temptable 
    unpivot (val for time in ([morning],[noon],[evening])) u 
) t
pivot (max(val) for indicator in ([Low],[High],[Avg])) p
order by 
    productid, VendorCode, date, 
    case time
     when 'Morning' then 1 
     when 'Noon' then 2 
     when 'Evening' then 3 
    end

case子句末尾的order by表达式确保结果正确排序(早晨,中午,晚上)。

答案 1 :(得分:0)

首先UNPIVOT然后PIVOT

SELECT
    piv.productid ,
    piv.date ,
    piv.VendorCode ,
    piv.Tmp AS [Time],
    piv.Low ,
    piv.High ,
    piv.Avg
from 
(  
    select *
    from #temptable
    unpivot
    (
      [Time]
      for [Tmp] in (morning, noon, evening)
    ) u
) src
pivot
(
  min([Time])
  for Indicator in ([Low], [High], [Avg])
) piv

结果:

productid   date        VendorCode  Time        Low     High    Avg
101         2016-08-05  202         evening     1       0       1
101         2016-08-05  202         morning     0       0       1
101         2016-08-05  202         noon        0       1       0
101         2016-08-06  202         evening     1       1       1
101         2016-08-06  202         morning     0       0       0
101         2016-08-06  202         noon        0       0       0