1

这是我之前问题的更新:多对多关系

以前的解决方案工作正常,但现在我想稍微改进一下结果。我想将所有波长值放在一行中。

因此,而不是以下结果:

DateTimeID  Wavelength  SensorID
11435   1581,665    334
11435   1515,166    334
11435   1518,286    335

我想要类似的东西:

DateTimeID  Wavelength1 Wavelength2  SensorID
11435   1581,665    1515,166     334
11435   1518,286                 335
4

1 回答 1

5

您可以使用将 a 应用于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

于 2013-02-25T15:21:13.283 回答