转换一些列&列标题成行SQL Server

时间:2015-12-03 21:16:34

标签: sql sql-server sql-server-2012

我有一个数据集(我写的查询的输出看起来像这样):

Date       Product  Sales10AM   Sales11AM
-----------------------------------------
10/1/2015   23        101           32
10/1/2015   24         34          343
10/2/2015   23         53           34
10/2/2015   24        443          343

我需要转换它看起来像这样:

Date    Product Time    Sales
-------------------------------
10/1/2015   23  1000    101
10/1/2015   23  1100    32
10/1/2015   24  1000    34
10/1/2015   24  1100    343
10/2/2015   23  1000    53
10/2/2015   23  1100    34
10/2/2015   24  1000    443
10/2/2015   24  1100    343

我尝试查看pivot,但我不确定如何将TimeColumn标头作为一行。有关如何进行此转换的任何建议吗?

2 个答案:

答案 0 :(得分:2)

您需要unpivot数据。

SQL Fiddle

select dt, product,
case when col = 'Sales10AM' then '1000' 
     when col = 'Sales11AM' then '1100' end as "time"
,sales from 
(select *
from yourdataset) p
unpivot
(sales for col in (Sales10AM,Sales11AM)) as u

答案 1 :(得分:0)

你可以使用unpivot结合案例或联合。

unpivot就像:

select dt, product,
case when col = 'Sales10AM' then '1000' else '1100' end as "time",
sales
 from  yourdataset
 unpivot
(
   sales for col in (Sales10AM,Sales11AM)
) as up

联合版本将如下所示:

select dt, product, '1000' as time, Sales10AM as sales
from yourdataset
union 
select dt, product, '1100' as time, Sales11AM as sales
from yourdataset
order by dt, product