SQL先进先出语句

很经典的“先进先出”的库存处理的SQL语句。

CREATE TABLE #tmp (
ID int IDENTITY (1, 1),
单价 decimal(18, 2) NOT NULL ,
数量 decimal(18, 2) NOT NULL ,
已出数量 decimal(18, 2) NOT NULL
)
insert into #tmp(单价,数量,已出数量) values(1.1,50,0)
insert into #tmp(单价,数量,已出数量) values(1.3,30,0)
insert into #tmp(单价,数量,已出数量) values(1.4,60,0)
insert into #tmp(单价,数量,已出数量) values(1.5,20,0)


declare @t decimal(18, 2),@temp decimal(18, 2)
set @t=90

update #tmp set @temp=case when @t>数量 then 数量 else @t end,数量=数量-@temp,@t=@t-@temp
from #tmp
where 单价<=1.30
select * from #tmp
go
drop table #tmp




CREATE TABLE #tmp (
ID int IDENTITY (1, 1),
单价 decimal(18, 2) NOT NULL ,
数量 decimal(18, 2) NOT NULL ,
已出数量 decimal(18, 2) NOT NULL
)
insert into #tmp(单价,数量,已出数量) values(1.1,50,0)
insert into #tmp(单价,数量,已出数量) values(1.3,30,0)
insert into #tmp(单价,数量,已出数量) values(1.4,60,0)
insert into #tmp(单价,数量,已出数量) values(1.5,20,0)


declare @t decimal(18, 2),@temp decimal(18, 2),@a varchar(8000)
select @t=60,@a=''

update #tmp set @temp=case when @t>数量-已出数量 then 数量-已出数量 else @t end, @t=@t-@temp,@a=@a+','+cast(@temp as varchar(10)),已出数量=@temp+已出数量 where 已出数量<>数量
select * from #tmp

set @t=30

update #tmp set @temp=case when @t>数量-已出数量 then 数量-已出数量 else @t end,@t=@t-@temp,@a=@a+','+cast(@temp as varchar(10)),已出数量=@temp+已出数量 where 已出数量<>数量
select * from #tmp

select right(@a,len(@a)-1)
go
drop table #tmp


--摘csdn 大力(pengdali)的贴
Top
posted @ 2005-05-25 11:38  azhai  阅读(2826)  评论(0编辑  收藏  举报