gpt4 book ai didi

mysql - 一个表中有 2 个结果的左连接,将相应表中的结果总和加倍

转载 作者:行者123 更新时间:2023-11-29 00:58:19 25 4
gpt4 key购买 nike

所以我在这里有这个查询,但我不知道如何更改行为。基本上它应该从 applications 表返回一组结果,付款表中的总付款具有相应的 id,费用表中的总费用具有相应的 id。当一次支付一次费用时,它的效果非常好。但是,在有 2 笔费用的情况下,付款似乎翻了一番。我假设如果有 3 笔费用,它会增加三倍,等等。

我尝试将 sum(distinct payments.amount) 作为付款,但问题是很可能会有 2 次付款完全相同的金额。我不确定是否可以喜欢,在有与金额相对应的不同 id 的地方求和。我仍在学习 SQL。

select applications.*,
permits.title as permit,
sum(payments.amount) as payments,
sum(fees.unitprice) as fees
from applications
left join permits on applications.permitid=permits.id
left join payments on payments.appid=applications.id
left join fees on fees.appid=applications.id
where applications.deleted=0
and payments.deleted=0
and fees.deleted=0
and fees.unitPrice > 0
and applicationdate between '1975-1-1' and '2011-2-10'
group by applications.id
order by permits.deptid,permits.title,status,dateissued,applicationdate

如有任何帮助,我们将不胜感激 - 我已经尝试修复此问题好几个小时了!花了我一些时间才弄清楚是什么原因造成的。

最佳答案

您可以在派生表中进行聚合并加入到该表中。

... join (SELECT fees.appid, sum(fees.unitprice) as fees
FROM fees
WHERE fees.deleted = 0
and fees.unitPrice > 0
GROUP BY fees.appid) aggregatedfees
on aggregatedfees.appid = applications.id
...

顺便说一句:此时您的所有左联接都被您的 where 子句转换为内部联接。

关于mysql - 一个表中有 2 个结果的左连接,将相应表中的结果总和加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4970630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com