2017-09-20 40 views
0

我的查詢顯示兩條結果。Oracle查詢 - 將多個結果合併成一行

查詢:

select /*+ parallel(16) */ * from CONTRACT where CONTRACT_ID ='1234'; 

結果:

_____________________________________________________________________________________ 
|CONTRACT_SOURCE | CONTRACT_ID | ROLE  | ROLE_ID | STD_CD | INDEX 
_____________________________________________________________________________________ 
|Source    | 1234  | role_driver | unique1 | LOAD | 9 
|Source    | 1234  | role_insured| unique2 | LOAD | 9 
_____________________________________________________________________________________ 

我想獲取這些結果合併,在下面的格式。

_____________________________________________________________________________________________________________________ 
|CONTRACT_SOURCE | CONTRACT_ID | ROLE  | ROLE_ID | ROLE   | ROLE_ID | STD_CD | INDEX | 
_____________________________________________________________________________________________________________________ 
|Source    | 1234  | role_driver | unique1 | role_insured | unique2 | LOAD | 9  | 
_____________________________________________________________________________________________________________________ 

我可以通過Oracle查詢來實現嗎?

+0

會有每contract_id只有兩個角色? – GurV

+0

是@GurV!正是 – Nidheesh

回答

1

您可以使用ROW_NUMBER和聚集,以獲得所需的多列旋轉:

select contract_source, 
    contract_id, 
    std_cd, 
    in, 
    max(case when rn = 1 then role end) as role_1, 
    max(case when rn = 1 then role_id end) as role_id_1, 
    max(case when rn = 2 then role end) as role_2, 
    max(case when rn = 2 then role_id end) as role_id_2 
from (
    select c.*, 
     row_number() over (
      partition by contract_source, contract_id, std_cd, in 
      order by role_id 
      ) as rn 
    from contract c 
    ) t 
group by contract_source, contract_id, std_cd, in 
+0

非常感謝@GurV! – Nidheesh

相關問題