22,210
社区成员
发帖
与我相关
我的任务
分享
所以该问题的核心在于如何不重复累计已统计的信息。
下面是个人观点:
为已参与统计的数据加上处理标识。如果在10000中加上一条记录,那直接就以最后的值+新增记录。
如果在已有的记录中做修改,则直接在累计字段+增量。
如果不这样处理,再好的SQL语句,再优秀的表设计也枉然.
declare @last_AccValue int
set @last_AccValue=(select top 1 AccValue from @t order by id desc)
insert into @t(length,AccValue) values(@length,@length+@last_AccValue)
create function getts(@id int)
returns bigint
as
begin
declare @ss bigint
select @ss=isnull(sum(length),0) from tsst where id<=@id
return @ss
end
go
create table tsst(id int,length int, AccValue as dbo.getts(id))
insert tsst(id,length)
select 1,10
union all select 2,30
union all select 3,40
union all select 4,70
union all select 5,90
declare @t table(id int,length int, AccValue int)
insert @t(id,length)
select 1,10
union all select 2,30
union all select 3,40
union all select 4,70
union all select 5,90
select id,
length,
(select sum(length)
from @t b
where b.id <= a.id) AccValue
from @t a
/*
id length AccValue
----------- ----------- -----------
1 10 10
2 30 40
3 40 80
4 70 150
5 90 240
*/
不希望只是简单实现,要说出具体的优劣