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

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

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

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

问题: 求教Sql语句,关于按日期扣库存

解决方案1:


create table 入库表
(货品名 varchar(10),日期 varchar(10),入库数量 int)
insert into 入库表
 select 'a','1.1',10 union all
 select 'a','3.1',5 union all
 select 'b','1.1',5 union all
 select 'c','1.2',10 union all
 select 'c','2.1',20 union all
 select 'd','1.1',10
create table 销售表
(货品名 varchar(10), 销售数量 int)
insert into 销售表
 select 'a',-12 union all
 select 'b',-3 union all
 select 'c',-5 union all
 select 'd',-10
with t as(
select c.*,
       'qtyout'=isnull(d.销售数量*-1,0)
 from
(select 货品名,日期,入库数量,
        'qtyin'=(select sum(b.入库数量) from 入库表 b where b.货品名=a.货品名 and b.日期<=a.日期)
 from 入库表 a) c
 left join 销售表 d on c.货品名=d.货品名),
u as
(select *,'fqty'=-1*case when qtyin<=qtyout then 入库数量
                         when qtyin>qtyout and qtyout-(qtyin-入库数量)>=0 then qtyout-(qtyin-入库数量)
                         when qtyin>qtyout and qtyout-(qtyin-入库数量)<0 then 0 
                         else 0 end
  from t)
select 货品名,日期,入库数量,销售数量=fqty,当前库存数量=入库数量+fqty
 from u
/*
货品名        日期         入库数量        销售数量        当前库存数量
---------- ---------- ----------- ----------- -----------
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
(6 row(s) affected)
*/

相关图片

相关文章