Mysql 先进先出消耗

Mysql FIFO consumption

我有2张桌子 article_receive , 以下列记录接收情况;

item   | title     |trans_id |qty|price|current_items | current_value
ADN231 | 12" Valve |jvn2333  |24 | 175 | 24           | 4200
ADN231 | 12" Valve |jvn2388  |12 | 185 | 36           | 6420

当前项目总是所有项目的总和

当前值是所有交易的总值 (4200 + 2220)

对于 Issuance ,我有 article_issue 以下列;

item   | title     | trans_id | qty 
ADN231 | 12" Valve | ISU2333  | 6
ADN231 | 12" Valve | ISU2401  | 24

我的要求是,我想创建一个消耗报告,它基本上使用 FIFO 方法计算每次发行的项目的确切数量。

article_issue 中的第 2 行有来自 2 笔交易的商品,并且有 2 个不同的价格。如何在MYSQL 8.0.15社区版.

中计算

目前,我正在使用这个SQL声明;

SELECT 
article_receives.id as RCVID, article_receives.item_id, article_receives.item_title, article_receives.quantity as rcv_qty,article_receives.transaction_id, article_receives.price as rate,
article_issues.id as ISUID,article_issues.quantity as isu_qty, article_issues.quantity * article_receives.price as value
FROM article_receives
LEFT JOIN article_issues ON article_receives.item_id = article_issues.item_id
ORDER BY article_receives.item_id
/** Some Column names are changed */

这为我提供了以下状态的数据; 请帮助我在 mysql 中创建正确的消耗报告。 旁注,这是在 laravel 5.8 中开发的应用程序,因此 eloquent 也可用。 谢谢

感谢 P.Salmon provided link FIFO 我能够解决问题。

MySql 查询是:

WITH 
  running_purchase AS
  ( SELECT transaction_id, created_at, quantity, item_id, price,
           SUM(quantity) OVER (PARTITION BY item_id
                               ORDER BY created_at, transaction_id
                               ROWS BETWEEN UNBOUNDED PRECEDING
                                        AND CURRENT ROW)
             AS running_total
    FROM article_receives
  ),
  running_stock AS
  ( SELECT demand_id, created_at, quantity, item_id, 
           SUM(quantity) OVER (PARTITION BY item_id
                               ORDER BY created_at, demand_id
                               ROWS BETWEEN UNBOUNDED PRECEDING
                                        AND CURRENT ROW)
             AS running_total
    FROM article_issues
  )
SELECT 
    s.demand_id, p.transaction_id,p.created_at as purchase_date, p.item_id, p.price, s.created_at as issue_date,
    LEAST(p.running_total, s.running_total) 
    - GREATEST(s.running_total - s.quantity, p.running_total - p.quantity)
        AS quantity
FROM running_purchase AS p
  JOIN running_stock AS s
    ON  p.item_id = s.item_id
    AND s.running_total - s.quantity < p.running_total  
    AND p.running_total - p.quantity < s.running_total 
WHERE s.created_at BETWEEN '2019-06-01' AND DATE_ADD('2019-06-30', INTERVAL 1 DAY)
ORDER BY
    p.item_id, p.created_at, p.transaction_id ;