mysql - 在 SQL Query 中仅对特定列进行分组和 FIFO 计算
问题描述
我有以下示例数据:
order_id receipt_id receipt_amount total_already_invoiced_amount
14 36 30 150
14 37 30 150
15 42 30 30
16 45 30 60
16 46 40 60
17 50 40 60
17 51 40 60
17 52 40 60
列receipt_amount 是该特定行收到的订单金额。列 total_already_invoiced_amount 是为订单开票的总金额。
我想将此表转换为一个新表,该表仅保留在扣除总发票金额后剩余的已收到金额的行(先进先出)。例如,如果我有 3 个收货行,每行 40 个,并且我的发票总数是 60,那么我可以计算出第一个收货行已开票,第二个收货行有 20 个剩余要开票,第三个有根本没有开票。我无法聚合,我必须将receipt_id 作为索引,因为它们可以有不同的日期,我需要能够据此进行区分。此类查询的结果如下:
order_id receipt_id received_not_invoiced_amount
16 46 10
17 51 20
17 52 40
我知道我可以选择 group byorder_id
来获得聚合的receipt_amount,但它也会聚合total_already_invoiced_amount,这不是我想要的。我正在尝试以下但不会执行 FIFO 计算....
SELECT order_id,
receipt_id,
(total_already_invoiced_amount -
(SELECT receipt_amount FROM X GROUP BY order_id)
) total_already_invoiced_amount
FROM X
WHERE (total_already_invoiced_amount -
(SELECT receipt_amount FROM X GROUP BY order_id)) < 0
我有点迷失从哪里开始做这项工作。
解决方案
你想要一个累积的总和:
select order_id, receipt_id,
least(running_ra, total_already_invoiced_amount), receipt_amount)
from (select x.*,
sum(receipt_amount) over (partition by order_id order by receipt_id) as running_ra
from x
) x
where running_ra > total_already_invoiced_amount
推荐阅读
- java - JButtons 消失了
- django - 如何在 Django 中使用 Celery 上传和处理大型 excel 文件?
- c# - 带有 Angular 12 的 .NET Core 2.2 - 在我重新编译之前不会加载站点
- google-cloud-platform - 在 terraform 中向 GCP 进行身份验证
- kotlin - 将具有列表的对象映射到具有列表的另一个对象
- python - 并非所有参数都在 SQL 语句中使用 - Python MySQL
- java - 使用 Flux 从服务中无限拉取
- javascript - 让按钮从关闭状态变为开启状态
- python - Python - 网络抓取中的列表超出范围错误
- scala - 多单元文件应该用小驼峰命名吗?