开发者

Left join where there are 2 results in one table, doubles the sum of results from a corresponding table

So I have this query here and I can't figure out how to change the behavior. Basically it's supposed to return a set of results from the applications table, with the total payments from the payments table with a corresponding id, and with the total fees from the fees table with the corresponding id. It works perfect when there's one payment for one fee. However, in cases where there are 2 fees, the payments seem to be doubling. I'd assume if there were 3 fees, it would triple, etc.

I tried doing sum(distinct payments.amount) as payments, but the problem is i开发者_如何学编程t's entirely likely that there'd be 2 payments for the exact same amount. I'm not sure if it's possible to like, do a sum where there's a distinct id corresponding to the amount.. I'm still learning 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

Any help would be appreciated - I've been trying to fix this for hours! Took me a few just to figure out what was causing it.


You can do the aggregation in a derived table and join onto that.

... 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 
 ...

BTW: All of your left joins are being converted to inner joins at the moment by your where clause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜