2015-06-19 171 views
1

我正在使用aws紅移,並且遇到了一個情況,那就是我有多個唯一ID的行,並且需要使用SQL將行組合到每個唯一ID的一列中。我搜索瞭如何做到這一點,它看起來像在postgres中是可能的,但是,建議的方法使用的功能如:string_agg和array_agg,這些功能在aws redshift中不可用。這甚至有可能使用紅移?有沒有人知道不使用函數來攻擊這個問題的方法?在Redshift中將多行轉換爲列

以下是我正在處理的內容。下表代表給我,我需要組建成每個ID一列的行查詢:

+----+----------+---------+-------+ 
| ID | make  | model | type | 
+----+----------+---------+-------+ 
| 1 | ford  | mustang | coupe | 
| 1 | toyota | celica | coupe | 
| 2 | delorean | btf  | coupe | 
| 2 | mini  | cooper | coupe | 
| 3 | ford  | mustang | coupe | 
| 3 |   |   |  | 
+----+----------+---------+-------+ 

什麼我希望直到結束:

+----+----------+---------+-------+----------+---------+-------+ 
| ID | make  | model | type | make  | model | type | 
+----+----------+---------+-------+----------+---------+-------+ 
| 1 | ford  | mustang | coupe | toyota | celica | coupe | 
| 2 | delorean | bttf | coupe | mini  | cooper | coupe | 
| 3 | ford  | mustang | coupe |   |  |  | 
+----+----------+---------+-------+----------+--------+--------+ 

回答

1

如果你的樣品數據表示你的數據,你只會有每個ID最多兩個條目,那麼你可以只加入到自身上而得到您所要求的輸出:

select id, a.make, a.model, a.type, b.make, b.model, b.type 
from yourtable a 
    left outer join yourtable b 
    on b.id = a.id 
    and b.make != a.make 
    and b.model != a.model 
    and b.type != a.type 

如果有兩個以上,你可以旋轉了一個簡單的控制檯AP在類似c#的東西中,讀入數據並寫出一個新表。

+0

謝謝!這真的有幫助 – user1026498