如何在 Oracle 中将行转置为列 sql

How to transpose the row to column in Oracle sql

我的基地table喜欢下面

我需要如下输出

谁能帮我解决这个问题

有条件地聚合数据。第 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>

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

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

这正是 pivot table 的用途:

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