2016-08-17 46 views
0
**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 

銷售表如何加減使用MySQL與時間戳庫存和銷售

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確定實際數帶時間戳。庫存每月採取一次,所以我加入了日曆表並顯示t他的日期和價值。 如果我是subtract from i.qty - s.qty它將在當天銷售單獨扣除如果我再次檢查第二天庫存將顯示100 .. 有人可以建議?!!

回答

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 
+0

消息209,級別16,狀態1,行233 不明確的列名'productqty'。不明確的列名'productqty'。我得到這個錯誤 – Krish

+0

@Krish:修改 – TheGameiswar

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的值爲負時,此查詢會將該值添加到結果中。如果它是積極的,它會減去它。

如果你想,在任何情況下,值應減去然後使用該查詢

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