如何不使用游标统计表内各项的值
比如我有一个表A,它包含两列,一个是编号Id,另一个是该编号的值Value:
1 342 566 181 425 2743 251 56...
DECLARE @A table (Type int, Id int, Value int);DECLARE @B table (Id int, Sum int);DECLARE @Cursor cursor, @Id int, @Value int;SET @Cursor = CURSOR FAST_FORWARD FOR SELECT Id, Value FROM @A;OPEN @Cursor;FETCH NEXT FROM @Cursor INTO @Id, @Value;WHILE @@FETCH_STATUS = 0 BEGIN IF NOT EXISTS (SELECT * FROM @B WHERE Id = @Id) INSERT @B (Id, Sum) VALUES (@Id, @Value); ELSE UPDATE @B SET Sum = Sum + @Value WHERE Id = @Id; FETCH NEXT FROM @Cursor INTO @Id, @Value; ENDCLOSE @Cursor;DEALLOCATE @Cursor;
create table A( id int, value int)create table B( id int, [sum] int)insert into A select 1,34 union allselect 2,56 union allselect 6,18 union allselect 1,42 union allselect 5,274 union allselect 3,25 union allselect 1,56 --先删后插delete from B where id in(select distinct id from A)insert into B select id,SUM(value) from A group by id--select * from B
[解决办法]
update b set b.[sum]=b.[sum]+a.ssumfrom tb b(select id,sum(value) as ssum from ta group by id)a on a.id=b.idinsert into tbselect id,sum(value) from ta where not exists(select 1 from tb where id=ta.id) group by id
[解决办法]
declare @T table(id int,v int)
insert into @T
select 1,34 union all
select 2,56 union all
select 6,18 union all
select 1,42 union all
select 5,274 union all
select 1,56 union all
select 2,56
declare @A table(id int,v int)
select id,sum(v) as sumV from @T group by id
insert into @A select id,sum(v) as sumV from @T group by id
select * from @A