【问题标题】:Mysql FIFO consumptionMysql FIFO消耗
【发布时间】:2019-05-13 06:28:41
【问题描述】:

我有 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)

对于发行,我有 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。 谢谢

【问题讨论】:

标签: mysql sql fifo laravel-5.8


【解决方案1】:

感谢P.Salmon 提供的链接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 ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多