oracle根据id的记录数将列转换为行

时间:2014-06-28 21:28:26

标签: sql oracle pivot

select *
    from(select C_TYPE_ID_EXT, C_ID_EXT, 
               row_number() over (partition by I_INTRN order by rank1) as rank
           from (select I_INTRN , C_TYPE_ID_EXT,C_ID_EXT,
                     row_number() over (partition by I_INTRN order by I_INTRN) rank1
                  from dex.dex_ej_rmpm_id
        )
where rank<=3;

以上查询给出了以下输出

rmpmid  C_TYPE_ID_EXT   C_ID_EXT    RANK
1             BEN         988-99      1
1             REGON       988-99      2
1             SIREN       988-99      3
2             BEN         988-99      1
2             REGON       988-99      2
2             SIREN       988-99      3
3             BEN         988-99      1
4             REGON       988-99      1

现在我通过在上面的查询中进行更改来寻找以下内容

rmpmid  type1   id1        type2    id2     type3   id3
1        Ben    988-99     Regon    988-99  siren   988-99
2        Ben    988-99     Regon    988-99  siren   988-99
3        ben    988-99              
4        regon  988-99  

我试图使用Pivot选项但无法找到解决方案 团队中的某些人可以帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合执行此操作:

select rmpmid,
       max(case when rank = 1 then C_TYPE_ID_EXT end) as type1,
       max(case when rank = 1 then C_ID_EXT end) as id1,
       max(case when rank = 2 then C_TYPE_ID_EXT end) as type2,
       max(case when rank = 2 then C_ID_EXT end) as id2,
       max(case when rank = 3 then C_TYPE_ID_EXT end) as type3,
       max(case when rank = 3 then C_ID_EXT end) as id3
from (select C_TYPE_ID_EXT, C_ID_EXT, rmpmid,
             row_number() over (partition by I_INTRN order by I_INTRN) as rank
      from dex.dex_ej_rmpm_id
     )
where rank <= 3
group by rmpmid;

两条评论:尽管结果如此,但您的查询没有rmpmid。我添加了它。其次,你不需要两级row_number()。内在的应该做你想做的事。