让我详细说明。我有一个这样的表(已更新以包含更多示例)
| id | date | cust | label | paid | due |
+----+-----------+------+-------------------------+------+-------+
| 1 |2016-02-02 | 1 | SALE: Acme Golf Balls | 0 | 1000 |
| 20 |2016-03-01 | 1 | PAYMENT: transaction #1 | 700 | 0 |
| 29 |2016-03-02 | 1 | PAYMENT: transaction #1 | 300 | 0 |
| 30 |2016-03-02 | 3 | SALE: Acme Large Anvil | 500 | 700 |
| 32 |2016-03-02 | 3 | PAYMENT: transaction #30| 100 | 0 |
| 33 |2016-03-03 | 2 | SALE: Acme Rockets | 0 | 2000 |
现在,我需要输出一个表,该表显示尚未全额支付的销售额和剩余金额。我怎么做?关于如何关联同一表中的行的信息很少。
编辑:这是我正在考虑的输出表
Table: debts_n_loans
| cust | label | amount |
==========================================
| 3 | SALE: Acme Large Anvil | 100 |
| 2 | SALE: Acme Rockets | 2000 |
最佳答案
如果cust
是将它们联系在一起的键,则可以只使用aggregation
和having
子句:
select cust, sum(paid), sum(due)
from t
group by cust
having sum(paid) <> sum(due);
如果需要详细信息,可以使用
join
,in
或exists
来获取详细信息。编辑:
如果您需要在字符串末尾使用事务来执行此操作:
select t.id, t.due, sum(tpay.paid) as paid
from t left join
t tpay
on tpay.label like '%#' || t.id
where t.label like 'SALE:%' and
tpay.label like 'PAYMENT:%'
group by t.id, t.due
having t.due <> sum(tpay.paid);
关于mysql - 在MySQL中选择相关行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35978518/