如何在Oracle sql中将行转换为列
我的基本表如下所示 我需要输出如下如何在Oracle sql中将行转换为列,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
有谁能有条件地在聚合数据方面帮助我。第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>
有条件地聚合数据。第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
你应该能用这样的东西
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
这正是我们的目的:
这正是我们的目的:
这些问题有没有回答你的问题?这些问题有没有回答你的问题?