在Oracle中如何根据记录行来转变为记录列
原始表内容
id name 金额 systemdate
1 A 101 2005-01-01
2 A 102 2005-01-02
3 A 103 2005-01-03
4 B 201 2005-02-02
5 B 202 2005-02-03
6 C 301 2005-03-01
转变后的内容
name 金额1 金额2 金额3
A 101 102 103//以name为标准,根据最大的记录行数相应数目的列数
B 201 202 0
C 301 0 0//其它记录少的用补零来填充
---------------------------------------------------------------
create table Test
(
id VARCHAR2(100) not null,
name VARCHAR2(1000) not null,
data NUMBER not null,
systemdate DATE
);
insert into Test(id,name,data,systemdate) values('1','A',101,to_date('2005-01-01','yyyy-MM-dd'));
insert into Test(id,name,data,systemdate) values('2','A',102,to_date('2005-01-02','yyyy-MM-dd'));
insert into Test(id,name,data,systemdate) values('3','A',103,to_date('2005-01-03','yyyy-MM-dd'));
insert into Test(id,name,data,systemdate) values('4','B',201,to_date('2005-01-01','yyyy-MM-dd'));
insert into Test(id,name,data,systemdate) values('5','B',202,to_date('2005-01-02','yyyy-MM-dd'));
insert into Test(id,name,data,systemdate) values('6','C',301,to_date('2005-01-01','yyyy-MM-dd'));
---------------------------------------------------------------
SQL> select * from Test
2 /
ID NAME DATA SYSTEMDATE
-------------------- -------------------- ---------- ----------
1 A 101 01-1月 -05
2 A 102 02-1月 -05
3 A 103 03-1月 -05
4 B 201 01-1月 -05
5 B 202 02-1月 -05
6 C 301 01-1月 -05
已选择6行。
select name,sum(decode(rn,1,data,0)) 金额1,
sum(decode(rn,2,data,0)) 金额2,
sum(decode(rn,3,data,0)) 金额3
from (select t.*,row_number() over(partition by name order by systemdate) rn from Test t)
group by name
NAME 金额1 金额2 金额3
-------------------- ---------- ---------- ----------
A 101 102 103
B 201 202 0
C 301 0 0