复杂的Pivot就像Oracle中的查询一样

时间:2014-11-17 18:16:14

标签: sql oracle plsql oracle-sqldeveloper

我在创建复杂的PL SQL查询时遇到了问题。

这是表格 - SQL Fiddle

ColumnA ColumnB ColumnC ColumnD ColumnE
A   Simple1    Para     Red     121
A   Simple1    Para     Blue    122
B   Simple2    Para     Red     123
B   Simple2    Para     Blue    124
C   Simple3    Para     Red     125
C   Simple3    Para     Blue    126
D   Simple4    Para     Red     127
D   Simple4    Para2    Blue    128
D   Simple4    Para3    Green   129

我期待这样的输出。

ColumnA ColumnB ColumnC Red Blue    Green
A   Simple1     Para    121 122     Null
B   Simple2     Para    123 124     Null
C   Simple3     Para    125 126     Null
D   Simple4     Para    127 128     129
D   Simple4     Para2   127 128     129
D   Simple4     Para3   127 128     129

2 个答案:

答案 0 :(得分:4)

假设我了解您的要求,根据您想要的结果,您希望按照columnacolumnb对红色,蓝色和绿色列进行分组,而不是在分组中包含columnc

要创建pivot,您可以使用maxcase。然后,您可以使用前两列和join distinct将这些结果返回原始表格:

SELECT DISTINCT
       t1.columna, 
       t1.columnb,
       t1.columnc,
       t2.red,
       t2.blue,
       t2.green
FROM Table1 t1
  JOIN (
      SELECT 
          ColumnA, 
          ColumnB, 
          max(case when columnd = 'Red' then columne end) red,
          max(case when columnd = 'Blue' then columne end) blue,
          max(case when columnd = 'Green' then columne end) green
      FROM Table1
      GROUP BY  columna, columnb
    ) t2 ON t1.columna = t2.columna AND t1.columnb = t2.columnb
ORDER BY t1.columna, t1.columnb, t1.columnc

答案 1 :(得分:4)

您还可以使用包含分析函数的pivot:

select columna,columnb,columnc,max(red) over (partition by columna,columnb), 
max(green) over (partition by columna,columnb), 
max(blue) over (partition by columna,columnb)
from (
select * from t pivot (max(columne) for columnd in ('Red' as red,'Green' as green,
'Blue' as blue) ))
order by 1,2,3