SQL Server Query for Many to Many Relationship - h

2019-06-06 04:44发布

This is an update to my previous question : Many to many relationship

The previous solution works fine, but now I want tgo improve the results a little bit. I´d like to have all the wavelength values in one row.

So instead of the following result :

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

I'd like to have something similar to this:

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

1条回答
Viruses.
2楼-- · 2019-06-06 05:08

You could use the following which applies a row_number() to the records:

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

See SQL Fiddle with Demo.

If you will have an unknown number of wavelength values, then you can use dynamic SQL to generate this:

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)

See SQL Fiddle with Demo

查看更多
登录 后发表回答