【问题标题】:MySQL split table amounts based on another table informationMySQL 根据另一个表信息拆分表的数量
【发布时间】:2022-01-18 19:03:28
【问题描述】:

我需要根据另一个相关的表信息(bill_details)来拆分表(交易)中的金额。

基表(事务):

ID amount document_id
1 100.00 11
2 80.00 12
3 120.00 13

另一个表(bill_details):

ID amount document_id description
1 20.00 11 A
2 60.00 11 B
3 20.00 11 C
4 80.00 12 D
5 60.00 13 E
6 20.00 13 F
5 20.00 13 G
6 40.00 13 H

我需要什么:

amount (splited from transactions) description (from row in description)
20.00 A
60.00 B
20.00 C
80.00 D
60.00 E
20.00 F
20.00 G
20.00 H

注意:有时“bill_details”金额的总和不等于“交易”金额。 一个账单可以有 0+ 笔交易。

我应该继续尝试在 MySQL 中还是应该使用 PHP?

【问题讨论】:

  • 你的问题没有意义,因为宿舍金额结果与账单金额相同,所以交易是如何进入的
  • 神奇的规则告诉你H是错误的,应该是20.00而不是E被改为40.00
  • 你有什么 MySQL 版本?

标签: php mysql split


【解决方案1】:

这有点复杂,但在 MySQL 8.0 中,您可以通过以下方式使用窗口函数:

SELECT 
    description,
    bill_details.amount + least(
        transactions.amount -
        SUM(bill_details.amount) OVER (PARTITION BY document_id ORDER BY bill_details.ID),
        0
    ) amount
    
FROM bill_details
JOIN transactions USING(document_id)
ORDER BY bill_details.ID

Live SQL fiddle

【讨论】:

  • 非常感谢,你帮了我很多。我知道我的问题不是很清楚,我的英语很有限,但不知何故你明白了。
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 2016-10-10
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多