那么这个问题的标题可能实际上并不能反映我想要的,我想不出更好的了。也许我应该在末尾附加一个“然后加入以这种方式获得的两个表”。
假设我有这张桌子。场景是,我们用 id 支付贷款loan_id
,我们将付款存储在“付款”表中,每笔付款都有自己的id
。当客户付款时,我们更改paid
为1
。
+---------+----+--------+------+
| loan_id | id | amount | paid |
+---------+----+--------+------+
| 1 | 1 | 1000 | 1 |
| 1 | 2 | 1000 | 1 |
| 1 | 3 | 1000 | 0 |
| 2 | 4 | 10000 | 0 |
| 3 | 5 | 20000 | 1 |
+---------+----+--------+------+
现在我们需要一份贷款报告。输出应如下所示:
+---------+-------+-----------+
| loan_id | paid | remaining |
+---------+-------+-----------+
| 1 | 2000 | 1000 |
| 2 | 0 | 10000 |
| 3 | 20000 | 0 |
+---------+-------+-----------+
该paid
列基本上是amount
pay = 1 的所有字段的remaining
总和。并且是 pay = 0 的行的总和。amount
它们应该按 分组loan_id
。
我尝试了什么:
我尝试了不同的连接、产品等,但我能从查询中得到的最好的结果是这个:
SELECT loan_id, SUM(paid), SUM(remaining)
FROM (
SELECT loan_id, 0 AS paid, SUM(amount) AS remaining
FROM Payment
WHERE paid = 0
GROUP BY loan_id
UNION
SELECT loan_id, SUM(amount) AS paid, 0 AS remaining
FROM Payment
WHERE paid = 1
GROUP BY loan_id
)
GROUP BY loan_id
但我想应该有比我更好的方法。