when i join two tables together and get the sum, i am getting the correct figure:
select
d.accn_id,
cast(d.load_date as DATE) as LoadDate,
cast (d.final_rpt_date as DATE) as FinalReportDate,
sum(p.paid_amt) as SumPaidAmt
from
accn_demographics d
join
accn_payments p
on
d.ACCN_ID=p.ACCN_ID
where
p.POSTED='y'
and p.PMT_DATE between '20120501' and '20120531'
group by
d.accn_id,
d.load_date,
d.final_rpt_date
however after i join ANOTHER table accn_payors:
select
d.accn_id,
cast(d.load_date as DATE) as LoadDate,
cast (d.final_rpt_date as DATE) as FinalReportDate,
sum(p.paid_amt) as SumPaidAmt
,payors.PAYOR_ID
from
accn_demographics d
join
accn_payments p
on
d.ACCN_ID=p.ACCN_ID
left join
accn_payors payors
on
payors.X_PAYOR_ID=p.X_PRICED_PAYOR_ID
and payors.ACCN_ID = p.ACCN_ID
where
p.POSTED='y'
and p.PMT_DATE between '20120501' and '20120531'
group by
d.accn_id,
d.load_date,
d.final_rpt_date
,payors.PAYOR_ID
i am getting an overstatement of sum(p.paid_amt)
the question is how can i adjust my join so that i am not joining multiple times?
Instead of joining on accn_payors, you need to join on a SELECT statement that returns one row per accn_id. Depending on your requirements, this might work.
Aliasing
min(x_payor_id)with the same name lets the rest of the code work without modification. That might or might not be a good idea. It’s a little misleading.So instead of this . . .
you’d do this . . .