关于sql:Transpose String column values to Row Oracle

Transpose String colomn values to Row Oracle

我的初始表是这样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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'

我的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

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


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

1
2
3
4
5
6
7
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)
 );

参考:
在 Oracle 行的多个列上使用数据透视

SQL FIDDLE