您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> MSSQL >> 求教Sql语句,关于按日期扣库存

求教Sql语句,关于按日期扣库存(3/3)

来源:网络整理     时间:2016/7/20 12:39:44     关键词:

关于网友提出的“ 求教Sql语句,关于按日期扣库存”问题疑问,本网通过在网上对“ 求教Sql语句,关于按日期扣库存”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: 求教Sql语句,关于按日期扣库存
解决方案2:

--> --> 
 
if not object_id('Tempdb..#入库表') is null
drop table #入库表
Go
Create table #入库表([货品名] nvarchar(1),[日期] decimal(18,1),[入库数量] int)
Insert #入库表
select N'a',1.1,10 union all
select N'a',3.1,5 union all
select N'b',1.1,5 union all
select N'c',1.2,10 union all
select N'c',2.1,20 union all
select N'd',1.1,10
Go
--> --> 
 
if not object_id('Tempdb..#销售表') is null
drop table #销售表
Go
Create table #销售表([货品名] nvarchar(1),[销售数量] int)
Insert #销售表
select N'a',-12 union all
select N'b',-3 union all
select N'c',-5 union all
select N'd',-10
Go
;with CTEStock
as
(
select *,(select SUM([入库数量]) from #入库表 where [货品名]=a.[货品名] and [日期]<=a.[日期]) sum入库数量 from #入库表 as a
)
select
a.[货品名],a.日期,a.入库数量,
销售数量=case when a.sum入库数量<=-b.[销售数量] then a.[入库数量]
when a.sum入库数量<-b.[销售数量]+a.[入库数量] then -b.销售数量-a.sum入库数量+a.[入库数量]
else 0 end 
,当前库存数量=case when a.sum入库数量<=-b.[销售数量] then 0
when a.sum入库数量<-b.[销售数量]+a.[入库数量]then  a.sum入库数量+b.[销售数量]  
else a.[入库数量] end
from CTEStock as a
left  join #销售表 as b on a.[货品名]=b.[货品名]  
/*
货品名 日期 入库数量 销售数量 当前库存数量
a 1.1 10 10 0
a 3.1 5 2 3
b 1.1 5 3 2
c 1.2 10 5 5
c 2.1 20 0 20
d 1.1 10 10 0
*/

以上介绍了“ 求教Sql语句,关于按日期扣库存”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/2827796_3.html

相关图片

相关文章