SQL语句批量更新如何写啊?

来源:百度知道 编辑:UC知道 时间:2024/06/05 05:57:49
编号 数量 数量合计
A1 1
C1 44
D1 55
A1 3
D1 5

上面是数据,我想通过SQL批量更行上述数据
得到的是如下:

编号 数量 数量合计
A1 1 4
C1 44 44
D1 55 60
A1 3 4
D1 5 60

也就是说 数量合计是把编号相同的数量合计然后分别写道每条记录的记录合计中。 编号不重复的就直接将数量合计 变更为 数量

谢谢各位了。
编号- 数量- 数量合计
A1- 1
C1- 44
D1- 55
A1- 3
D1- 5

上面是数据,我想通过SQL批量更行上述数据
得到的是如下:

编号 -数量- 数量合计
A1- 1- 4
C1 - 44 - 44
D1- 55 - 60
A1- 3 - 4
D1- 5- 60

--> --> (Roy)生成测试数据

if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([编号] nvarchar(2),[数量] int,[数量合计] int)
Insert #T
select N'A1',1,null union all
select N'C1',44,null union all
select N'D1',55,null union all
select N'A1',3,null union all
select N'D1',5,null
Go
--更新
update a
set [数量合计]=(select sum([数量]) from #T where [编号]=a.[编号])
from #T a
--or
update a
set [数量合计]=b.[数量]
from
#T a,(select [编号],sum([数量])[数量] from #T group by [编号])b
where a.[编号]=b.[编号]

select * from #T