2017-05-04 46 views
0

這兩個表都已經存在,所以沒有查找動態情況。目標是水平合併數據行,但將它們放在最左邊的「數據」字段中。永遠不會有第四個條目。將行更新到不同的列

我使用Microsoft SQL Server

表1:

ID|Data 
-------- 
A | 1 
A | 2 
B | 3 
C | 4 
C | 5 
C | 6 

表2:

ID | Data 1 | Data 2 | Data 3 
------------------------------ 
A |  |  | 
B |  |  | 
C |  |  |  

期望表2的結果:

ID | Data 1 | Data 2 | Data 3 
------------------------------ 
A | 1 | 2 | 
B | 3 |  | 
C | 6 | 7 | 8 
+0

爲什麼要以這種格式存儲數據?通常情況下,你會以這種格式顯示它,但不能以這種方式存儲它。 – ollie

+0

您正在使用哪個數據庫? – GurV

回答

1

您可以使用row_number

select id, 
    max(case when rn = 1 then data end) as data_1, 
    max(case when rn = 2 then data end) as data_2, 
    max(case when rn = 3 then data end) as data_3 
from (
    select t.*, 
     row_number() over (
      partition by id order by data 
      ) as rn 
    from your_table t 
    ) t 
group by id;