【问题标题】:How to transpose the row to column in Oracle sql如何在Oracle sql中将行转置为列
【发布时间】:2021-06-13 11:03:43
【问题描述】:

我的基本表如下所示

我需要如下输出

谁能帮我解决这个问题

【问题讨论】:

标签: sql oracle oracle11g pivot


【解决方案1】:

有条件地聚合数据。 #1 - 11 行中的样本数据;查询从第 12 行开始。

SQL> with base (type, branch, count) as
  2    (select 'deposit' , 101, 100 from dual union all
  3     select 'deposit' , 102, 150 from dual union all
  4     select 'deposit' , 103, 200 from dual union all
  5     select 'transfer', 101, 50  from dual union all
  6     select 'transfer', 102, 100 from dual union all
  7     select 'transfer', 103, 150 from dual union all
  8     select 'withdraw', 101, 25  from dual union all
  9     select 'withdraw', 102, 50  from dual union all
 10     select 'withdraw', 103, 75  from dual
 11    )
 12  select branch,
 13    sum(case when type = 'deposit'  then count end) deposit,
 14    sum(case when type = 'transfer' then count end) transfer,
 15    sum(case when type = 'withdraw' then count end) withdraw
 16  from base
 17  group by branch
 18  order by branch
 19  /

    BRANCH    DEPOSIT   TRANSFER   WITHDRAW
---------- ---------- ---------- ----------
       101        100         50         25
       102        150        100         50
       103        200        150         75

SQL>

【讨论】:

    【解决方案2】:

    你应该可以使用这样的东西

    SELECT Branch,
           SUM(CASE WHEN Type = 'deposit' THEN Count ELSE NULL END) Deposit,
           SUM(CASE WHEN Type = 'transfer' THEN Count ELSE NULL END) Transfer,           
           SUM(CASE WHEN Type = 'withdraw' THEN Count ELSE NULL END) Withdraw           
    FROM <table_name>
    GROUP BY Branch
    

    【讨论】:

      【解决方案3】:

      这正是pivot table 的用途:

      select *
      from <table>
      pivot (
        sum(count)
        for type in (
          'deposit' as DEPOSIT,
          'transfer' as TRANSFER,
          'withdraw' as WITHDRAW
        )
      )
      

      【讨论】:

        猜你喜欢
        • 2016-12-03
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        相关资源
        最近更新 更多