将字符串colomn值转置为Row Oracle

时间:2017-12-22 14:31:57

标签: sql oracle oracle11g oracle12c

我的初始表是这样的。

CREATE TABLE pivot_string ( col1 NUMBER, col2 NUMBER, col3 VARCHAR2(6), 
 col3_id NUMBER, col3_desc VARCHAR2(10) ) ; 
 INSERT INTO pivot_string SELECT 123, 9875,'RO', 40, 'Roma' FROM dual;
 INSERT INTO pivot_string SELECT 123, 9875,'IT', 40, 'iteration' FROM dual;
 INSERT INTO pivot_string SELECT 123, 9875,'US', 78, 'world' FROM dual;
 INSERT INTO pivot_string SELECT 123, 9875,'WE', 56, 'WHAT' FROM dual;
 COMMIT;
 SELECT * FROM pivot_string;
 -- INSERT INTO pivot_string SELECT 123, 4875,'RO', 55, 'Roma' FROM dual;
 --INSERT INTO pivot_string SELECT 124, 4875,'RO', 44, 'Roma' FROM dual;

 table: pivot_string'
------------------------------------------
col1 |  col2 | col3 | col3_id | col3_desc
-----------------------------------------
123  |  9875 | 'RO' |   40    | 'Roma' 
123  |  9875 | 'IT' |   50    | 'iteration'
123  |  9875 | 'US' |   78    | 'world'
123  |  9875 | 'WE' |   56    | 'WHAT'

Excepted- pivot_string
--------------------------------------------------------------------------
col1 |  col2 | ro | ro_desc | it | it_desc     | us | us_desc | we | we_desc
---------------------------------------------------------------------------
123  |  9875 | 40 |  'Roma' | 50 | 'iteration' | 78 | 'world' | 56 | 'WHAT'

我的方法

WITH mytest AS(  
SELECT a.col1, a.col2, a.col3,a.col3_id, a.col3_desc
FROM pivot_string a 
   )
 SELECT coalesce(RO.col1,IT.col1, US.col1, WE.col1)col1,  
   coalesce(RO.col2,IT.col2, US.col2, WE.col2) col2,
   RO,RO_desc IT,IT_desc, US,US_desc, WE, WE_desc
  FROM(

  (SELECT col1,col2, col3_id RO, col3_desc RO_desc FROM mytest WHERE col3 = 
 'RO' )RO
  LEFT JOIN (SELECT col1,col2, col3_id IT, col3_desc IT_desc FROM mytest 
  WHERE col3 = 'IT' )  IT 
       ON(RO.col1 =IT.col1 AND RO.col2 = IT.col2)
   LEFT JOIN ( SELECT col1,col2, col3_id US, col3_desc US_desc FROM mytest 
   WHERE col3 = 'US' )US
      ON(RO.col1 =US.col1 AND RO.col2 = US.col2)
    LEFT JOIN (SELECT col1,col2, col3_id WE, col3_desc WE_desc FROM mytest 
      WHERE col3 = 'WE') WE 
      ON(RO.col1 =WE.col1 AND RO.col2 = WE.col2)
    ) ;

我解决这个问题的方式并不好,因为col3有超过100个不同的值。   所以左派加入我所做的肯定不是正确的方法。   由于col3和col3_desc,我无法使用pivot。他们的类型是Varchar2

有人知道解决此类问题的更好方法吗?

1 个答案:

答案 0 :(得分:2)

我几天前看到过类似的问题。你可以在PIVOT中添加多个聚合函数。检查以下查询:

select * from (
select * from pivot_string
) PIVOT 
(
  SUM(COL3_ID) as id,MIN(COL3_DESC) as descp 
  for col3 in ('RO' as RO, 'IT' as IT, 'US' as US, 'WE' as WE)
 );

参考: Using pivot on multiple columns of an Oracle row

SQL FIDDLE