计算产品库存

时间:2017-03-26 08:02:05

标签: mysql yii2

我有商店产品信息的表Bill Detail。

当我用价格输入产品并输入存储库和数量时。

我通过获取具有存储库和数量的产品ID获得输出产品

现在我需要计算存储库中的产品库存。

示例:

Bii详细资料:

Type    Product_ID Repository_id Qty
1       2          2             1
1       2          2             3
2       2          2             1
1       2          3             2
1       2          3             3
2       2          3             2

注意:键入:1:输入,2:输出

Folow数据:存储库2中产品2的总库存有:

  Total Input - Total output = (1+3) - 1 = 3

我需要sql: - 列出所有存储库都有产品:产品2的示例,有2个存储库2和3 - 包含存储库的产品总库存:示例,包含产品2和存储库3.总库存为3。

那么我如何使用SQL进行查询呢?

1 个答案:

答案 0 :(得分:2)

在SQL中 基于类型

,您可以使用sum和group by和case
  select 
      Product_ID
    , Repository_id
    , sum(case when type = 1 then Qty 
               when typ2 = 2 then -Qty
          END) total
  from my_table 
  group by       
      Product_ID
    , Repository_id
相关问题