Oracle查询 - 将多个结果合并到一行中

时间:2017-09-20 09:40:31

标签: sql 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查询实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

您可以使用row_number和aggregation来获取所需的多列旋转:

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
相关问题