**Inventory Table**:
StoreNo Date ProductBarCode ProductQty
61 2016-02-28 2017961746012 100
61 2016-02-29 2017961746012 100
61 2016-03-01 2017961746012 100
61 2016-03-02 2017961746012 100
61 2016-03-03 2017960624045 100
61 2016-03-04 2017961746012 100
75 2016-03-04 2017960624045 90
61 2016-03-05 2017961746012 100
促销表:
StoreNo Date ProductBarCode SaleQty
61 2016-02-29 2017961746012 8
75 2016-03-04 2017960624045 0
61 2016-03-01 2017961746012 2
61 2016-03-04 2017961746012 -5
期望的输出:
StoreNo Date ProductBarCode ProductQty
61 2016-02-28 2017961746012 100
61 2016-02-29 2017961746012 92
61 2016-03-01 2017961746012 90
61 2016-03-02 2017961746012 90
61 2016-03-03 2017960624045 100
61 2016-03-04 2017961746012 95
75 2016-03-04 2017960624045 90
61 2016-03-05 2017961746012 93
我希望通过计算带有时间戳的(INVENTORY + ALL ADDITIONAL PRODUCTS COMING IN) - ALL SOLD PRODUCTS
来确定实际数字。每月一次采用库存。所以我加入了日历表并显示日期和值。
如果我是subtract from i.qty - s.qty
它会在那天单独减去销售,如果我再次检查第二天库存将显示100 ..
有人可以建议吗?!!
答案 0 :(得分:0)
SELECT i.StoreNo,i.Date,i.ProductBarCode,(i.ProductQty-s.ProductQty) AS ProductQty
FROM Inventory i
LEFT JOIN Sale s ON i.ProductBarCode=s.ProductBarCode
当SaleQty on Sale表的值为负时,此查询将该值添加到结果中。如果它是正数,它将减去它。
如果您想在任何情况下减去该值,请使用此查询
SELECT i.StoreNo,i.Date,i.ProductBarCode,(i.ProductQty-ABS(s.ProductQty)) AS ProductQty
FROM Inventory i
LEFT JOIN Sale s ON i.ProductBarCode=s.ProductBarCode
答案 1 :(得分:0)
select i.storeno,i.datee,i.productbarcode,
isnull(i.productqty-(select sum(saleqty) as runningsum from #salestable t where t.date<=i.datee and t.storeno=i.storeno),i.productqty) as tproductqty
from #inventory i
left join
#salestable s
on s.storeno=i.storeno
and s.productbarcode=i.productbarcode
and s.date=i.datee
输出
storeno datee productbarcode productqty
61 2016-02-28 2017961746012 100
61 2016-02-29 2017961746012 92
61 2016-03-01 2017961746012 90
61 2016-03-02 2017961746012 90
61 2016-03-03 2017960624045 90
61 2016-03-04 2017961746012 95
75 2016-03-04 2017960624045 90
61 2016-03-05 2017961746012 95