【问题标题】:Complex Pivot like query in OracleOracle 中的复杂枢轴式查询
【发布时间】:2015-01-14 17:57:01
【问题描述】:

我在创建复杂的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

【问题讨论】:

  • 您遇到了什么麻烦 - 您尝试过什么?您的意思是 PL/SQL,还是 Oracle 风格的 SQL?
  • 那么你的输出出现在哪里?您是否正在寻找一个返回引用光标的函数?显示您将从中调用它的上下文可能会有所帮助。您的 Fiddle 没有任何 PL/SQL 或任何尝试的代码。了解您使用的 Oracle 版本可能也很有用。
  • 为什么Para2Para3 行保留了它们丢失的Para 行中的值,反之亦然;您想根据 ColumnA/ColumnB 的分组来合并结果吗?请你也解释一下你的逻辑吗?

标签: sql oracle plsql oracle-sqldeveloper


【解决方案1】:

假设我了解您的要求,考虑到您想要的结果,您希望将红色、蓝色和绿色列按columnacolumnb 分组,不包括分组中的columnc

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

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

【讨论】:

    【解决方案2】:

    您还可以使用具有分析功能的数据透视:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多