SQL Server使用unpivot与新表

时间:2013-07-09 22:44:32

标签: sql sql-server-2008 unpivot

我不是一个真正的程序员,所以我对一般编程和SQL的了解比这里任何人都少。我不确定这个问题是否容易,但我真的不知道如何开始。所以,我有一张名为Photonics的表:

enter image description here

我想更改它,以便结果将显示在这样的新表中:

Name        Timestamp   Value
Photonics   1/1/12 0:15 239.04
Photonics   1/1/12 0:30 247.68
Photonics   1/1/12 0:45 253.44
Photonics   1/1/12 1:00 254.88
Photonics   1/1/12 1:15 253.44
Photonics   1/1/12 1:30 239.04
Photonics   1/1/12 1:45 239.04
Photonics   1/1/12 2:00 239.04
Photonics   1/1/12 2:15 239.04
Photonics   1/1/12 2:30 250.56

有人告诉我这叫做Pivot!而且我觉得这个话题对我这样的初学者来说太复杂了。

1 个答案:

答案 0 :(得分:4)

将数据列转换为行的过程称为UNPIVOT。有几种方法可以解决数据:

您可以使用UNION ALL查询:

select 'Photonics' name, dt + cast('12:15 AM' as datetime) timestamp, [12:15 AM] as value
from Photonics
union all
select 'Photonics' name, dt + cast('12:30 AM' as datetime) timestamp, [12:30 AM] as value
from Photonics
union all
select 'Photonics' name, dt + cast('12:45 AM' as datetime) timestamp, [12:45 AM] as value
from Photonics;

请参阅SQL Fiddle with Demo

您可以在SQL Server 2005 +中使用UNPIVOT函数:

select 'Photonics' name,
  timestamp = dt + cast(timestamp as datetime),
  value
from photonics p
unpivot
(
  value
  for timestamp in ([12:15 AM], [12:30 AM], [12:45 AM], [1:00 AM], [1:15 AM])
) unpiv;

请参阅SQL Fiddle with Demo

您可以在SQL Server 2008 +中使用CROSS APPLY和值:

select 'Photonics' name,
  timestamp = dt + cast(timestamp as datetime),
  value
from photonics p
cross apply
(
  values
  ('12:15 AM', [12:15 AM]),
  ('12:30 AM', [12:30 AM]),
  ('12:45 AM', [12:45 AM]), 
  ('1:00 AM', [1:00 AM]),
  ('1:15 AM', [1:15 AM])
) c (timestamp, value);

请参阅SQL Fiddle with Demo