先进先出SQL Server 语句

--> 测试数据:[m]
if object_id('[m]') is not null drop table [m]
go 
Create table m ( ID int not NULL , mCount int not NULL ,mTime datetime not null) 
INSERT into m(ID,mCount,mTime) 
SELECT 1,50,'2014-02-01' UNION ALL
SELECT 1,60,'2014-02-02' UNION ALL
SELECT 2,50,'2014-02-01' UNION ALL
SELECT 2,60,'2014-02-03' UNION ALL
SELECT 2,60,'2014-02-04' UNION ALL
SELECT 2,40,'2014-02-02' UNION ALL
SELECT 1,70,'2014-02-03' UNION ALL
SELECT 1,80,'2014-02-04' 

select * from m
/*
ID          mCount      mTime
----------- ----------- -----------------------
1           50          2014-02-01 00:00:00.000
1           60          2014-02-02 00:00:00.000
2           50          2014-02-01 00:00:00.000
2           60          2014-02-03 00:00:00.000
2           60          2014-02-04 00:00:00.000
2           40          2014-02-02 00:00:00.000
1           70          2014-02-03 00:00:00.000
1           80          2014-02-04 00:00:00.000

(8 行受影响)

*/

declare @i int 
set @i =80  --定义出货总数量
select a.id,a.mcount ,a.mtime,
case when a.mcount-(a.tmcount-@i) <0 then 0  when a.tmcount<@i then a.mcount else a.mcount-(a.tmcount-@i)end as '出货数量' 
from
(
select a.*,sum(isnull(b.mcount,0)) as Tmcount from m a left join m b on a.mtime>=b.mtime and a.id=b.id
group by a.id,a.mcount,a.mtime
)a 
/*
id          mcount      mtime                   出货数量
----------- ----------- ----------------------- -----------
1           50          2014-02-01 00:00:00.000 50
1           60          2014-02-02 00:00:00.000 30
1           70          2014-02-03 00:00:00.000 0
1           80          2014-02-04 00:00:00.000 0
2           40          2014-02-02 00:00:00.000 30
2           50          2014-02-01 00:00:00.000 50
2           60          2014-02-03 00:00:00.000 0
2           60          2014-02-04 00:00:00.000 0

(8 行受影响)

*/

一般来说,在实际业务中不可能所有的种类都是出库80;这里仅做一个例子,来看看多个种类的效果。

在很多业务中,每种物品出库的数量是不一样的,所以在先进先出的时候需要循环每个物品。

ps.本例没取用同一天进货两次的情况;如果一天进货两次,需要先进行按天按品种进行汇总后再出库。(有的货物不看进货日期,而是看有效期、或者批号、批次;所以分组条件也需要跟着更新。eg.药品,可能今天进的是1号生产的,而昨天进的是3号生产的;在出库时,需要先出今天进的1号生产的。)


阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页