【问题标题】:Oracle: transpose column to rowOracle:将列转置为行
【发布时间】:2021-03-30 10:42:04
【问题描述】:

我有下表中的数据

  bins  |   pro
  -------------
    1   |   0.10
    2   |   0.05
    3   |   0.78
    4   |   0.20 
    5   |   0.82
    6   |   0.45

我需要一个带有这个结果的查询:

   1    |   2   |   3   |   4   |   5   |   6
-------------------------------------------------
  0.10  | 0.05  |  0.78 |  0.20 |  0.82 |  0.45

【问题讨论】:

  • this 回答你的问题了吗?

标签: sql oracle pivot aggregate-functions


【解决方案1】:

对于固定的 bin 列表,可以进行条件聚合:

select 
    max(case when bins = 1 then pro end) as bins1,
    max(case when bins = 2 then pro end) as bins2
    ...
    max(case when bins = 6 then pro end) as bins6
from mytable

【讨论】:

    【解决方案2】:

    或者,使用pivot 本身:

    SQL> with data (bins, pro) as
      2  -- sample data
      3    (select 1, 0.1  from dual union all
      4     select 2, 0.05 from dual union all
      5     select 3, 0.78 from dual union all
      6     select 4, 0.2  from dual union all
      7     select 5, 0.82 from dual union all
      8     select 6, 0.45 from dual
      9    )
     10  -- pivoting begins here
     11  select *
     12  from (select bins, pro
     13        from data
     14       )
     15  pivot
     16    (max(pro)
     17     for bins in (1, 2, 3, 4, 5, 6)
     18    )
     19  ;
    
        1     2     3     4     5     6
    ----- ----- ----- ----- ----- -----
     0.10  0.05  0.78  0.20  0.82  0.45
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多