mysql - 如何使用带有时间戳的MySQL减去库存和销售

标签 mysql sql

库存表:

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

我想通过计算带有时间戳的(库存+所有附加产品进来)-所有已售产品来确定实际数量。库存每月进行一次。所以我加入了日历表并显示日期和值。 如果我从 i.qty - s.qty 中减去,如果我第二天再次检查库存将显示 100,那么仅在当天销售期间就会减去。 有人可以建议吗?!!

最佳答案

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

关于mysql - 如何使用带有时间戳的MySQL减去库存和销售,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38992328/

相关文章:

SQL优先条件

PHP 没有通过本地套接字连接到 MYSQL

python - 如何将两个不同 python 列表的元素插入到 MySQL 表中的两个不同行?

mysql - 通过 mysql 语句获取 select...group 的行数

mysql - sql - 如何获取 module=5 的类(class)

SQL Server 过滤索引 - 谁能解释我看到的这个错误?

sql - 在尝试更改之前如何检查数据库中是否使用了行?

MySQL 密码在 Windows 中被 powershell 修改

java - centos 无法连接mysql

mysql - 如何更新表数组