I'm having a problem with my LEFT OUTER JOIN on 3 tables, with a SUM clause. This is my code:
SELECT r.ret_desc, vmp.vlt_id,
SUM((vmp.cash_in + vmp.per_cash_in_sec)
+ (CASE WHEN vmp.acc_id = t.db_id AND t.txn_type_id = 1 THEN t.amount ELSE 0 END)
- (CASE WHEN vmp.acc_id = t.cr_id AND t.txn_type_id = 1 THEN t.amount ELSE 0 END)) AS in_adj,
FROM ret AS r
LEFT OUTER JOIN vmp ON r.acc_id = vmp.acc_id
LEFT OUTER JOIN txn AS t ON (r.acc_id = t.credit_acc_id OR r.acc_id = t.debit_acc_id)
WHERE t.txn_type_id IN (1,2,4,5)
GROUP BY r.ret_desc, vmp.vlt_id
;
The problem is that there are multiple VMP records and the SUM field gets multiplied by the COUNT of the VMP records. Ex: If the SUM field should equal $100 and there are 50 VMP records, then the SUM becomes $5000, when it should just be $100. Does anyone know what is wrong with this statement?