今天在ITPUB看到一个人问的语句问题:http://www.itpub.net/thread-1734957-1-1.html
parent_id emp_id emp_name total_amout
每个员工的总销售额=自己的销售额+其下级员工的总销售额,
Andrew = 200_100_120_80_50=550
我用递归+游标实现了一下,总感觉应该有更好的实现方式,下面是我的实现方式:
WITH recur(parent_id , emp_id , emp_name , total_amout,tlevel)
select parent_id , emp_id , emp_name , total_amout,0 as tlevel
SELECT a.parent_id , a.emp_id , a.emp_name , a.total_amout,b.tlevel+1
from emp as a INNER join recur b ON a.parent_id=b.emp_id
select @level=max(tlevel) FROM emp_ext
declare cursor_t cursor local static read_only forward_only
select emp_id from emp_ext where tlevel=@level-1
FETCH NEXT FROM cursor_t into @temp
update emp_ext set total_amout=(SELECT sum(total_amout) from emp_ext where parent_id=@temp)+(SELECT total_amout from emp_ext where emp_id=@temp)
FETCH NEXT FROM cursor_t into @temp
为了便于大家测试,我把生成表和数据的代码也复制如下:
INSERT into emp(parent_id , emp_id , emp_name , total_amout)
VALUES (NULL , 2 , 'Andrew' , 200)
INSERT into emp(parent_id , emp_id , emp_name , total_amout)
VALUES (2 , 1 , 'Nancy', 100)
INSERT into emp(parent_id , emp_id , emp_name , total_amout)
VALUES (2 , 3 , 'Janet' , 120)
INSERT into emp(parent_id , emp_id , emp_name , total_amout)
VALUES (3 , 4 , 'Michael' , 80)
INSERT into emp(parent_id , emp_id , emp_name , total_amout)
VALUES (1 , 5 , 'Robert' , 50)
本文转自CareySon博客园博客,原文链接:http://www.cnblogs.com/CareySon/archive/2012/11/01/2749962.html,如需转载请自行联系原作者