【发布时间】:2021-06-13 11:03:43
【问题描述】:
【问题讨论】:
-
这些是否回答了您的问题? stackoverflow.com/…
标签: sql oracle oracle11g pivot
【问题讨论】:
标签: sql oracle oracle11g pivot
有条件地聚合数据。 #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
)
)
【讨论】: