2013-02-25 227 views
1

這是我對上一個問題的更新:Many to many relationship針對多對多關係的SQL Server查詢 - 如何查詢?

以前的解決方案工作正常,但現在我想要改善一點結果。我想將所有波長值都放在一行中。

因此,而不是結果如下:

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

什麼關係數據庫管理系統? SQL Server,Db2,Oracle?和版本?猜測SQL Server自上一篇文章標記它。 – xQbert 2013-02-25 15:19:06

+0

一個波長取決於SensorID? – Arion 2013-02-25 15:19:07

+0

您的示例與文本不匹配。該示例具有3個相同ID的波長分佈在2行上。 – 2013-02-25 15:20:00

回答

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

+0

謝謝!你爲什麼使用最大功能? – patex1987 2013-02-25 15:25:07

+0

@ patex1987'pivot'需要一個聚合函數。由於「波長」是一個字符串,因此您需要使用'min'或'max'。 – Taryn 2013-02-25 15:26:40

+0

現在很明顯。再次感謝您 – patex1987 2013-02-25 15:28:11