注册 登录
编程论坛 SQL Server论坛

实在没招了,求助!

fyqabc 发布于 2010-05-19 16:45, 772 次点击
有一个表,如下:

产品 单据 数量
1010 入库 100
1010 入库 50
1010 出库 70


要求,减掉出库后,数量为0的入库就删除,入库数量小于出库数量,就继续用其余入库减出库,直到大于0,如下结果

结果:
产品 单据 数量
1010 入库 80

还有很多其它产品,这个存储过程该怎么写呢,,谢谢!
2 回复
#2
aei1352010-05-20 20:31
create proc p_test
as
begin
delete from table where 产品 in(
select 产品 from table group by 产品 having sum(case when 单据='入库' then 数量 when 单据='出库' then -数量 end)=0)
select 产品,单据,sum(case when 单据='入库' then 数量 when 单据='出库' then -数量 end) 数量
 from table group by 产品,单据
end

#3
fyqabc2010-05-21 10:36
TKS!
1