把分都给了,请教一个实例性问题!关于分级汇总的存语句
大家好!
例表字段及数据例子如下:
用户名 上级用户 个人业绩 累计业绩
a 0 10 0
b a 10 0
c a 10 0
d b 10 0
e d 10 0
汇总后效果
a 0 10 40
b a 10 20
c a 10 0
d b 10 10
e d 10 0
也就是本人的累计业绩等于他所有的下级用户的个人业绩合计,0表示没有上级!
请问有没有好的算法!
我写了一个存储过程,大家看看没什么错误,还没有没更简单一点的算法
//////我的思路是把每个人的上一级名子找出来放到一个字段中,然后在跟根这个字段进行过滤求合计:
CREATE PROCEDURE dgl_sumje @ls_msg varchar(50) output
AS
declare @hybh varchar (14)
declare @gryj numeric(18, 0)
declare @fwyj numeric(18, 0)
declare @dbrbh varchar(14)
declare @fdbr varchar(300)
declare @ls_dbrbh varchar(14)
declare @ls_dbrbh_2 varchar(14)
declare @je numeric(18, 0)
BEGIN TRANSACTION
CREATE TABLE #tmp (
hybh varchar (14) COLLATE Chinese_PRC_CI_AS NOT NULL ,
gryj numeric(18, 0) NULL ,
fwyj numeric(18, 0) NULL ,
dbrbh varchar(14) NULL,
fdbr varchar(300) null
)
if @@error<>0/*建立临时补助公式表失败*/
begin
select @ls_msg='建立临时失败'
ROLLBACK TRANSACTION
return
end
insert into #tmp select hybh,gryj,fwyj,dbrbh,'' from dgl_test
if @@error<>0/*向临时表插入数据失败*/
begin
select @ls_msg='向临时表插入数据失败'
ROLLBACK TRANSACTION
return
end
print 'ok'
DECLARE cur_cyxx CURSOR FOR
select hybh,gryj,fwyj,dbrbh,fdbr
from #tmp
OPEN cur_cyxx
fetch next from cur_cyxx
into @hybh,@gryj,@fwyj,@dbrbh,@fdbr
while @@Fetch_status=0
begin
print @hybh
set @ls_dbrbh=@dbrbh
if @ls_dbrbh='0'
begin
goto txts
-- CONTINUE
end
update #tmp set fdbr='|'+dbrbh where hybh=@hybh
while 1=1
begin
set @ls_dbrbh_2=(select dbrbh from #tmp where hybh=@ls_dbrbh)
if @ls_dbrbh_2='0'
begin
update #tmp set fdbr=fdbr+'|' where hybh=@hybh
break
end
update #tmp set fdbr=fdbr+'|'+@ls_dbrbh_2 where hybh=@hybh
set @ls_dbrbh=@ls_dbrbh_2
end
txts:
fetch next from cur_cyxx
into @hybh,@gryj,@fwyj,@dbrbh,@fdbr
end
close cur_cyxx
DEALLOCATE cur_cyxx
GO
上面的存储过程有几个错误的地方没找出来,请大家给看一下!
务器: 消息 512,级别 16,状态 1,过程 dgl_sumje,行 47
[Microsoft][ODBC SQL Server Driver][SQL Server]子查询返回的值多于一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
@RETURN_VALUE = N/A