我应该开始说我正在使用postgresql。我有四个表,customer_orders,payment和clearinghouse_orders。 Customer_orders是支付和清算所订单的一对多。
当我使用此查询时,我的总数是正确的:
SELECT mailers.mail_date, SUM(cho.remit) AS remits
FROM mailers
RIGHT JOIN customer_orders co
ON mailers.id = co.mailer_id
LEFT JOIN clearinghouse_orders cho
ON co.id = cho.customer_order_id
GROUP BY mailers.mail_date
汇款总额是完美的。当我添加付款表时,佣金会增加。我怀疑当我添加付款时,它开始计算两次付款的两次付款。以下是需要更正的代码:
SELECT mailers.mail_date, SUM(cho.remit) AS remits, SUM(p.payment_amt) AS payments
FROM mailers
RIGHT JOIN customer_orders co
ON mailers.id = co.mailer_id
LEFT JOIN clearinghouse_orders cho
ON co.id = cho.customer_order_id
LEFT JOIN payments p
ON co.id = p.customer_order_id
GROUP BY mailers.mail_date
我是SQL的初学者,所以请放轻松我。我们将非常感谢您提供的任何帮助。
答案 0 :(得分:1)
如果您的理论是正确的,那么删除重复付款行的简单子查询应解决这个问题......
SELECT mailers.mail_date, SUM(cho.remit) AS remits, SUM(p.payment_amt) AS payments
FROM mailers
RIGHT JOIN customer_orders co
ON mailers.id = co.mailer_id
LEFT JOIN clearinghouse_orders cho
ON co.id = cho.customer_order_id
LEFT JOIN
(
select
customer_order_id,
sum(payment_amt) as payment_amt
from
payments
group by
customer_order_id
) as p
ON co.id = p.customer_order_id
GROUP BY mailers.mail_date