Sql server 将多列移动到行,将一行作为列

Sql server 将多列移动到行,将一行作为列,sql-server,sql-server-2012,sql-server-2008-r2,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 #temptabl

我在一个临时表中得到了查询结果,该临时表如下所示:

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
我需要输出如下所示:


我看了一下如何使用枢轴,但这似乎只适用于聚合?有没有简单的方法可以做到这一点?

首先执行
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

通过首先应用
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

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

输出中的Low、High、Avg值背后的逻辑是什么这里没有逻辑。它直接来自数据库,我的意思是我猜不出这些值是如何得到表中的值的。。相同的映射到输出。没有可能的副本