- 论坛徽章:
- 0
|
横表变纵表的问题
横表变纵表,如果仅两列的话可以用我的方法,如果列数多了,确实用一条语句不容易处理。
/work_dev/test$cat aaa
create table acc_tmp (cust_id int, acc_id varchar(9), fee bigint );
insert into acc_tmp values( 123,'a1',100);
insert into acc_tmp values( 123,'a2',200);
insert into acc_tmp values( 456,'a1',300);
insert into acc_tmp values( 456,'a2',400);
create table addr_tmp (cust_id int, address varchar(19) );
insert into addr_tmp values( 123,'here');
insert into addr_tmp values( 456,'their');
/work_dev/test$cat bbb
with temp (row_id,cust_id,acc_id,fee,address )as (
select ROW_NUMBER() over() as a ,c.cust_id,c.acc_id,c.fee,d.address from acc_tmp c left outer join addr_tmp d on (c.cust_id=d.cust_id))
select a.cust_id,a.address,a.acc_id,a.fee,b.acc_id,b.fee,a.fee+b.fee as allfee from (select * from temp where mod(row_id,2)=1)as a,
(select * from temp where mod(row_id,2)=0) as b where a.cust_id=b.cust_id;
/work_dev/test$db2 -tvf bbb
with temp (row_id,cust_id,acc_id,fee,address )as ( select ROW_NUMBER() over() as a ,c.cust_id,c.acc_id,c.fee,d.address from acc_tmp c left outer join addr_tmp d on (c.cust_id=d.cust_id) order by c.cust_id) select a.cust_id,a.address,a.acc_id,a.fee,b.acc_id,b.fee,a.fee+b.fee as allfee from (select * from temp where mod(row_id,2)=1)as a, (select * from temp where mod(row_id,2)=0) as b where a.cust_id=b.cust_id
CUST_ID ADDRESS ACC_ID FEE ACC_ID FEE ALLFEE
----------- ------------------ -------- -------------------- -------- -------------------- --------------------
123 here a1 100 a2 200 300
456 their a1 300 a2 400 700
2 条记录已选择。
[ 本帖最后由 @龙井茶 于 2006-8-9 16:27 编辑 ] |
|