我有以下模型,我想编写一个返回未使用积分的查询。积分有很多费用,而这些费用又会有很多退款。到目前为止,我对查询的尝试如下,但我发现它有问题,需要一点帮助。所有amount
列都是正数。
Credit
id (integer)
amount (decimal)
Charge
id (integer)
credit_id (integer)
amount (decimal)
Refund
id (integer)
charge_id (integer)
amount (decimal)
我的查询如下所示:
SELECT credits.*,
"credits"."amount" - coalesce(sum("charges"."amount"), 0) + coalesce(sum("refunds"."amount"), 0) AS unspent_amount
FROM "credits"
LEFT OUTER JOIN "charges" ON "charges"."credit_id" = "credits"."id"
LEFT OUTER JOIN "refunds" ON "refunds"."charge_id" = "charges"."id"
GROUP BY "credits"."id"
HAVING "credits"."amount" > coalesce(sum("charges"."amount"), 0) - coalesce(sum("refunds"."amount"), 0) LIMIT 1
我遇到的问题是,如果一项费用有很多退款,那么费用金额的总和将为 N*,其中 N 是退款次数。我只想为每个费用 ID 计算一次费用金额。
最终,我想要积分,其中 credits.amount > charge_against_credits.amount 的总和-refunds_for_those_charges.amount。我怎样才能做到这一点?
编辑:
以下是一些将重现问题的示例记录:
credits
id 1
amount 25.0
charges
id 1
credit_id 1
amount 25.0
refunds
id 1
charge_id 1
amount 20.0
-----------
id 2
charge_id 1
amount 5.0
编辑2:
预期输出:
credits:
1 row:
id: 1, amount: 25.0, unspent_amount: 25.0