一个先进先出进销存的问题:
进货队列,如下表,按时间顺序进货。知道已出货数量120 ,先进先出, 用SQL求未出货数据
进货队列:ID,进货数mCount ,进货时间mTime .
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 1,70,'2014-02-03' UNION ALL
SELECT 1,80,'2014-02-04'
SQL返回结果:
ID,进货数mCount ,进货时间mTime,已出货数
1,70,'2014-02-03' 10--这里标示部分出货。
1,80,'2014-02-04' 0
即,已出货的120为最先进货的 50+60+(70-10)
假设mTime进货时间是不重复的。求SQL语句
------解决方案--------------------
--Create table m ( ID int not NULL , mCount int not NULL ,mTime datetime not null)
--INSERT into m(ID,mCount,mTime)
--SELECT 2,50,'2014-02-01' UNION ALL
--SELECT 2,60,'2014-02-02' UNION ALL
--SELECT 2,70,'2014-02-03' UNION ALL
--SELECT 2,80,'2014-02-04'
/*
ID,进货数mCount ,进货时间mTime,已出货数
1,70,'2014-02-03' 10--这里标示部分出货。
1,80,'2014-02-04' 0
*/
;WITH cte AS (
SELECT *,ROW_NUMBER()OVER(PARTITION BY id ORDER BY mtime)oid
FROM m),cte2 AS
(
SELECT * ,120-mcount AS [剩余数量]
FROM cte
WHERE oid=1
UNION ALL
SELECT a.id,a.mcount,a.mtime,a.oid,CASE WHEN b.[剩余数量]-a.mcount>=0 THEN b.[剩余数量]-a.mcount ELSE 0 END [剩余数量]--b.[剩余数量]
FROM cte a INNER JOIN cte2 b ON a.oid=b.oid+1 AND a.id=b.id
)
SELECT id,mcount,mtime,(SELECT [剩余数量] FROM cte2 b WHERE a.id=b.id AND a.oid-1=b.oid)[已出货数]
FROM cte2 a
WHERE mcount>(SELECT [剩余数量] FROM cte2 b WHERE a.id=b.id AND a.oid-1=b.oid)
ORDER BY id,oid
/*
id mcount mtime 已出货数
----------- ----------- ----------------------- -----------
1 70 2014-02-03 00:00:00.000 10
1 80 2014-02-04 00:00:00.000 0
2 70 2014-02-03 00:00:00.000 10
2 80 2014-02-04 00:00:00.000 0
*/
------解决方案--------------------
select a.id,a.mcount ,a.mtime,a.tmcount,
case when a.mcount-(a.tmcount-120) <0 then 0 else a.mcount-(a.tmcount-120)end as '出货' from
(
select a.*,sum(isnull(b.mcount,0)) as Tmcount from m a left join m b on a.mtime>=b.mtime
group by a.id,a.mcount,a.mtime
)a
where a.mcount>(a.mcount-(a.tmcount-120))
id mcount mtime tmcount 出货
----------- ----------- ----------------------- ----------- -----------
1 70 2014-02-03 00:00:00.000 180 10
1 80 2014-02-04 00:00:00.000 260 0
(2 行受影响)