-1

当我将两个表连接在一起并得到总和时,我得到了正确的数字:

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)

问题是如何调整我的加入,以免我多次加入?

4

2 回答 2

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
于 2012-08-20T23:53:52.340 回答
1

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

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
于 2012-08-20T23:55:07.350 回答