日期:2014-05-18 浏览次数:20444 次
1 34 2 56 6 18 1 42 5 274 3 25 1 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; END CLOSE @Cursor; DEALLOCATE @Cursor;
create table A ( id int, value int ) create table B ( id int, [sum] int ) insert into A 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 3,25 union all select 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.ssum from tb b (select id,sum(value) as ssum from ta group by id)a on a.id=b.id insert into tb select 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