Dynamically pivoting a table Oracle

后端 未结 1 1447
一整个雨季
一整个雨季 2020-11-27 20:46

I have a table that looks like this:

C_ID   P_ID   KEY    VALUE
null   null   KEY1   VALUE1
null   null   KEY2   VALUE2
null   null   KEY3   VALUE3
2       2         


        
相关标签:
1条回答
  • 2020-11-27 21:05

    This can be done dynamically the following way. First, here is the static version of the query so you can see the final sql:

    select c_id,
      p_id,
      max(case when r_key= 'KEY1' then r_value  end) KEY1,
      max(case when r_key= 'KEY2' then r_value  end) KEY2,
      max(case when r_key= 'KEY3' then r_value  end) KEY3,
      max(case when r_key= 'KEY4' then r_value  end) KEY4,
      max(case when r_key= 'KEY5' then r_value  end) KEY5
    from s_projectroles
    group by c_id, p_id
    

    See SQL Fiddle with Demo

    Then to do this dynamically, you can create the following procedure:

    CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
    as
        sql_query varchar2(1000) := 'select c_id, P_id ';
    
        begin
            for x in (select distinct r_key from s_projectroles order by 1)
            loop
                sql_query := sql_query ||
                  ' , max(case when r_key = '''||x.r_key||''' then r_value end) as '||x.r_key;
    
                    dbms_output.put_line(sql_query);
            end loop;
    
            sql_query := sql_query || ' from s_projectroles group by c_id, p_id';
    
            open p_cursor for sql_query;
        end;
    /
    

    Then to execute it:

    variable x refcursor
    exec dynamic_pivot(:x)
    print x
    

    The result is the same:

    |   C_ID |   P_ID |   KEY1 |   KEY2 |   KEY3 |   KEY4 |   KEY5 |
    ----------------------------------------------------------------
    | (null) | (null) | VALUE1 | VALUE2 | VALUE3 | (null) | (null) |
    |      2 |      2 | (null) | (null) | (null) | VALUE4 | (null) |
    |      2 |      3 | (null) | (null) | (null) | (null) | VALUE5 |
    
    0 讨论(0)
提交回复
热议问题