请教一个sql语句

yangzhy 2007-12-27 05:56:28
表如下:

id amount
1 100
2 80
3 72
4 51
……

想实现:
删除 amount 合计 小于 200 的数据
(对于上表,就是删除id为1,2的数据。并把第三条数据 改为 100+80+72 - 200)

是不是有点麻烦,谢谢高手了:)
...全文
138 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangzhy 2008-01-09
  • 打赏
  • 举报
回复
啥也不说了,太感谢楼上的哥们了!
谢谢“平友”!我用了你的语句。也谢谢“背着灵魂漫步”和其他回帖的朋友!
这就结贴。
utpcb 2007-12-29
  • 打赏
  • 举报
回复
忘记你最后的条件了不好意思现在加上

create table tb(id int,amount int)
insert tb select 1,100
insert tb select 2,80
insert tb select 3,72
insert tb select 4,51
declare @sum int,@id int
select @sum=sum(amount)from tb t2
where (select sum(amount)from tb t1 where t1.id<=t2.id)<200
delete from tb where (select sum(amount)from tb t1 where t1.id<= tb.id)<200
select @sum=@sum+(select top 1 amount from tb)-200
select @id=min(id) from tb
update t1
set amount=@sum
from tb t1
where id=@id
select *from tb
drop table tb
-----
3 52
4 51



utpcb 2007-12-29
  • 打赏
  • 举报
回复
create table tb(id int,amount int)
insert tb select 1,100
insert tb select 2,80
insert tb select 3,72
insert tb select 4,51


select * from tb
select * from tb t2 where (select sum(amount)from tb t1 where t1.id<= t2.id)<200
delete from tb where (select sum(amount)from tb t1 where t1.id<= tb.id)<200
select *from tb
drop table tb
-----
1 100
2 80
3 72
4 51
--------
1 100
2 80
---
3 72
4 51


看到没有?
delete from tb where (select sum(amount)from tb t1 where t1.id<= tb.id)<200这一句就可以



pt1314917 2007-12-29
  • 打赏
  • 举报
回复
晕。又能看到了。什么垃圾论坛。。靠```
pt1314917 2007-12-29
  • 打赏
  • 举报
回复
我记得我昨天回过帖的
怎么不见了?奇怪。。
我从“我的社区”—“我参与的帖子”也可以看到这个帖子,但就是没有我的回复。。。
这样的问题发现N多次了,有人在删贴?
还是CSDN数据库的数据经常会丢失或者出现其他问题?
pt1314917 2007-12-28
  • 打赏
  • 举报
回复

create table tb(id int,amount int)
insert tb select 1,100
insert tb select 2,80
insert tb select 3,72
insert tb select 4,51


declare @i int
set @i=0
update tb set amount=@i-200,@i=@i+amount

delete tb where amount<0
wzy_love_sly 2007-12-27
  • 打赏
  • 举报
回复
declare @tb table (id int,am int)
insert into @tb select 1,100
insert into @tb select 2,80
insert into @tb select 3,72
insert into @tb select 4,51

declare @i int,@sum int
select @i=count(1) from @tb
select @sum=max(su) from (
select * ,su=(select sum(am) su from @tb where id<=a.id ) from @tb a )a
while @sum>200
begin
delete @tb where id=(select min(id) from @tb)
select @sum=max(su) from (
select * ,su=(select sum(am) su from @tb where id<=a.id ) from @tb a )a
end
select * from @tb


id am
3 72
4 51
liangCK 2007-12-27
  • 打赏
  • 举报
回复
create table tb(id int,amount int)
insert tb select 1,100
insert tb select 2,80
insert tb select 3,72
insert tb select 4,51

declare @i int
set @i=0

update tb set @i=@i+amount,
amount=@i

delete tb where amount<200

select * from tb

drop table tb

/*
id amount
----------- -----------
3 252
4 303

(所影响的行数为 2 行)
*/

27,582

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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