sql >> Base de Datos >  >> RDS >> Sqlserver

Consulta de SQL Server para una relación de muchos a muchos:¿cómo consultar?

Podría usar lo siguiente que aplica un row_number() a los registros:

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

Consulte SQL Fiddle con demostración .

Si tendrá un número desconocido de wavelength valores, entonces puede usar SQL dinámico para generar esto:

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)

Consulte SQL Fiddle con demostración