| 很經典的“先進先出”的庫存處理的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)的貼
 
 |