17,377
社区成员
发帖
与我相关
我的任务
分享
--在网友原文(http://topic.csdn.net/t/20020711/11/866042.html)的基础上作了些修改,参考一下:
SQL> drop table test_tree;
Table dropped
SQL> create table test_tree
2 (
3 userid number(8) not null primary key,
4 username varchar2(18) not null,
5 p_username varchar2(18),
6 num number(10,2)
7 );
Table created
SQL> insert into test_tree values(1,'1000',null,null);
1 row inserted
SQL> insert into test_tree values(2,'1100','1000',null);
1 row inserted
SQL> insert into test_tree values(3,'1200','1000',null);
1 row inserted
SQL> insert into test_tree values(4,'1101','1100',100);
1 row inserted
SQL> insert into test_tree values(5,'1102','1100',200);
1 row inserted
SQL> insert into test_tree values(6,'1104','1100',250);
1 row inserted
SQL> insert into test_tree values(7,'1201','1200',150);
1 row inserted
SQL> insert into test_tree values(8,'1205','1200',200);
1 row inserted
SQL> insert into test_tree values(9,'1207','1200',150);
1 row inserted
SQL> commit;
Commit complete
SQL> select * from test_tree;
USERID USERNAME P_USERNAME NUM
--------- ------------------ ------------------ ------------
1 1000
2 1100 1000
3 1200 1000
4 1101 1100 100.00
5 1102 1100 200.00
6 1104 1100 250.00
7 1201 1200 150.00
8 1205 1200 200.00
9 1207 1200 150.00
9 rows selected
SQL> select b.username,
2 b.p_username,
3 (select distinct sum(nvl(a.num, 0))
4 from test_tree a
5 start with a.username = b.username
6 connect by a.p_username = prior a.username) sum
7 from test_tree b
8 start with username = '1000'
9 connect by p_username = prior username;
USERNAME P_USERNAME SUM
------------------ ------------------ ----------
1000 1050
1100 1000 550
1101 1100 100
1102 1100 200
1104 1100 250
1200 1000 500
1201 1200 150
1205 1200 200
1207 1200 150
9 rows selected
SQL>