问一个问题,这样的表数据如何更新...

longwycn 2005-08-03 11:47:03
ID PartNo Qty Total
1 A 1 0
2 A 10 0
3 A 20 0
4 A 15 0

想根据Qty的数量加到Total下面.结果应该如下:
ID PartNo Qty Total
1 A 1 1
2 A 10 11
3 A 20 31
4 A 15 46

请问SQL语句如何写....
...全文
144 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
longwycn 2005-08-03
  • 打赏
  • 举报
回复
好象不行.先谢谢回复.使用子查询...
vivianfdlpw 2005-08-03
  • 打赏
  • 举报
回复
update 表
set [Total]=]=(select sum(Qty) from 表 where ID<=t.ID)
from 表 t
vivianfdlpw 2005-08-03
  • 打赏
  • 举报
回复
select *,
[Total]=(select sum(Qty) from 表 where ID<=t.ID)
from 表 t
chenyuandxm 2005-08-03
  • 打赏
  • 举报
回复
tb_name是你的表名。
chenyuandxm 2005-08-03
  • 打赏
  • 举报
回复
错了,不要“Qty”+:
select ID ,PartNo,Qty,Total=(Qty+Total) from tb_name where ID=1
union
select ID ,PartNo,Qty,Total=select Total=sum(Qty) from tb_name where ID in(1,2)) from tb_name where ID=2
union
select ID ,PartNo,Qty,Total=select Total=sum(Qty) from tb_name where ID in(1,2,3)) ) from tb_name where ID=3
union
select ID ,PartNo,Qty,Total=select Total=sum(Qty) from tb_name where ID<>4 ) from tb_name where ID=4
GRLD8888 2005-08-03
  • 打赏
  • 举报
回复
不好意思,修改应该是这样的

update a set total=(select sum(qty) from a where b.id>=id) from a b
chenyuandxm 2005-08-03
  • 打赏
  • 举报
回复
昨天刚给人做过一个相减的,比减法简单一点,用一个select语句:类似楼上
select ID ,PartNo,Qty,Total=(Qty+Total) from tb_name where ID=1
union
select ID ,PartNo,Qty,Total=Qty+(select Total=sum(Qty) from tb_name where ID in(1,2)) from tb_name where ID=2
union
select ID ,PartNo,Qty,Total=Qty+(select Total=sum(Qty) from tb_name where ID in(1,2,3)) ) from tb_name where ID=3
union
select ID ,PartNo,Qty,Total=Qty+(select Total=sum(Qty) from tb_name where ID<>4 ) from tb_name where ID=4
GRLD8888 2005-08-03
  • 打赏
  • 举报
回复
select id,partno,qty, (select sum(qty) from a where b.id>=id) total from a b
vivianfdlpw 2005-08-03
  • 打赏
  • 举报
回复
declare @tb table
(
ID int,
PartNo varchar(10),
Qty int,
Total int
)
insert @tb
select 1,'A',1,0 union
select 2,'A',10,0 union
select 3,'A',20,0 union
select 4,'A',15,0
--测试
update @tb
set [Total]=(select sum(Qty) from @tb where ID<=t.ID)
from @tb t

--查看
select * from @tb

--结果
/*
ID PartNo Qty Total
----------- ---------- ----------- -----------
1 A 1 1
2 A 10 11
3 A 20 31
4 A 15 46

(所影响的行数为 4 行)
*/
longwycn 2005-08-03
  • 打赏
  • 举报
回复
想想办法吗

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧