加入另一个表会导致总和更大

时间:2012-08-20 23:29:13

标签: sql sql-server sql-server-2008 tsql

当我将两张桌子连在一起并获得总和时,我得到了正确的数字:

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

然而,在我加入另一张表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

我对sum(p.paid_amt)

的夸大其词

问题是如何调整我的联接以便我不会多次加入?

2 个答案:

答案 0 :(得分:1)

这可能会有效,但我不知道决定你想要获得哪个payor_id会是什么,所以min()可能不适合你,也许max()会吗?

SELECT * 

FROM (

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,
    min(p.X_PRICED_PAYOR_ID)


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
) payments
LEFT JOIN accn_payors payors
on  
    payors.X_PAYOR_ID=payments.X_PRICED_PAYOR_ID 
    and payors.ACCN_ID = payments.ACCN_ID

答案 1 :(得分:1)

您需要加入一个每个accn_id返回一行的SELECT语句,而不是加入accn_payors。根据您的要求,这可能会有效。

select accn_id, min(x_payor_id) x_payor_id
from payors
group by accn_id

使用相同名称的别名min(x_payor_id)可以使其余代码无需修改即可运行。这可能是也可能不是一个好主意。这有点误导。

所以不要这样。 。

left join 
    accn_payors payors
on  
    payors.X_PAYOR_ID=p.X_PRICED_PAYOR_ID 
    and payors.ACCN_ID = p.ACCN_ID
你会这样做的。 。

left join 
    (select accn_id, min(x_payor_id)
     from payors
     group by accn_id) payors
on  
    payors.x_payor_id = p.x_priced_payor_id
    and payors.accn_id = p.accn_id