组查询中的Oracle Pivot列

时间:2016-07-17 10:07:14

标签: oracle pivot oracle-apex

我有以下工作查询:

WITH pivot_data AS (
             select PSGROUP,
    PSCOLUMN as PSCOLUMN
FROM LOG_PS_STATUS
            )
    SELECT *
    FROM   pivot_data
    PIVOT (
           MAX(NULL)        --<-- pivot_clause
          FOR PSCOLUMN--<-- pivot_for_clause        
        IN  (&PS_COLUMNS.)   --<-- pivot_in_clause         

);

它显示了预期的结果:

值:

PSGroup PSColumn
A           1
A           2
A           3
B           1
B           2
B           3
C           3

结果如下:

  

PSGroup(垂直列)PSColoumn(水平)

           1 2 3
A
B
C

现在我想将PSGroup列作为PSColumn组,输出应该是:

A
 1 2 3
B 
 1 2 3
C
 3

1 个答案:

答案 0 :(得分:1)

您可以使用listagg:

WITH pivot_data(PSGroup,PSColumn) AS (
    select 'A',           1 FROM dual UNION all
    select 'A',           2 FROM dual UNION all
    select 'A',           3 FROM dual UNION all
    select 'B',           1 FROM dual UNION all
    select 'B',           2 FROM dual UNION all
    select 'B',           3 FROM dual UNION all
    select 'C',           3 FROM DUAL),

    res(PSGroup,PSColumns) as(
     SELECT PSGroup, LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)
        FROM   pivot_data
        GROUP BY PSGroup)

    select DECODE(PSColumns,NULL,PSGroup,NULL) AS PSGroup, PSColumns from(
    select PSGroup, NULL as PSColumns from res
      union all
    select PSGroup, PSColumns from res)t
      ORDER BY t.PSGroup, t.PSColumns NULLS first

另请注意,LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)限制为4000个字符