如何计算每手的手头数量 (mysql)

How to calculate quantity on hand for every lot (mysql)

这是transaction details table

我正在尝试设计一个 Mysql 库存数据库。 我认为每 type: 1 行一个产品批次。

对于每笔交易,type 列有 1 代表 IN 和 0 代表 OUT。 detail_id 引用了 id 列。

我怎样才能得到这个结果:

 id   item  sum(quantity)
  1     1         3            [10-(5+2)]
  4     1         0            (5-5)
  6     2         20            20
WITH cte AS (
  SELECT *, 
         SUM(detail_id IS NULL) OVER (PARTITION BY item ORDER BY id) group_num 
  FROM details
)
SELECT MIN(id) id,
       item,
       SUM( CASE type WHEN 1 THEN quantity 
                      WHEN 0 THEN -quantity 
                      END ) `sum(quantity)`
FROM cte
GROUP BY item, group_num;

fiddle

你可以使用这个:

SELECT 
  lots.id,
  MIN(lots.item) AS item,
  MIN(lots.quantity) - IFNULL(SUM(details.quantity), 0) AS quantity 
FROM (
  SELECT id, item, quantity 
  FROM details
  WHERE type = 1
) lots LEFT JOIN details ON lots.id = details.detail_id 
GROUP BY lots.id
ORDER BY lots.id

demo on dbfiddle.uk

我修改了你的fiddle。我确实对您现有的 table 进行了更改 - 您需要指定 detail_id,只要它为空,以便我们可以将结果分组。

最终查询看起来像

select detail_id, item, 
(in_sum - out_sum) as `sum(quantity)` from
(SELECT
detail_id,
item,
sum(case when type=1 then quantity else 0 end) as in_sum,
sum(case when type=0 then quantity else 0 end) as out_sum
FROM details
group by detail_id, item) tab

首先通过对 detail_id 个项目进行分组来获取指定类型的数量总和,然后使用该结果计算最终输出。