SQL Server查询多对多关系 - 如何查询?

时间:2013-02-25 15:16:43

标签: sql sql-server-2008 many-to-many pivot

这是对上一个问题的更新:Many to many relationship

之前的解决方案工作正常,但现在我想要tgo一点点改善结果。我希望将所有波长值放在一行中。

所以不是以下结果:

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

1 个答案:

答案 0 :(得分:5)

您可以使用以下内容将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