你可以使用它適用一個row_number()
的記錄如下:
select DateTimeID,
[1] as Wavelength1,
[2] as Wavelength2,
SensorId
from
(
select [DateTimeID], [Wavelength], [SensorID],
row_number() over(partition by DateTimeID, SensorId
order by DateTimeID) rn
from yourtable
) src
pivot
(
max(Wavelength)
for rn in ([1], [2])
) piv
參見SQL Fiddle with Demo。
如果你將有數目不詳的wavelength
值,那麼你可以使用動態SQL生成這個:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Wavelength'+cast(rn as varchar(50)))
from
(
select row_number() over(partition by DateTimeID, SensorId
order by DateTimeID) rn
from yourtable
) src
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT DateTimeID,' + @cols + ', SensorId from
(
select [DateTimeID], [Wavelength], [SensorID],
''Wavelength''+cast(row_number() over(partition by DateTimeID, SensorId
order by DateTimeID) as varchar(50)) rn
from yourtable
) x
pivot
(
max(Wavelength)
for rn in (' + @cols + ')
) p '
execute(@query)
見SQL Fiddle with Demo
什麼關係數據庫管理系統? SQL Server,Db2,Oracle?和版本?猜測SQL Server自上一篇文章標記它。 – xQbert 2013-02-25 15:19:06
一個波長取決於SensorID? – Arion 2013-02-25 15:19:07
您的示例與文本不匹配。該示例具有3個相同ID的波長分佈在2行上。 – 2013-02-25 15:20:00