我正在尝试获取total_pay_amt> 2000的所有人员的列表。我只需要包含最近的sched_pymt_amt,它由总数中每笔贷款的sched_pymt_amt_eff_dt确定。下面的代码几乎满足了我的需要,除了“having sum(sched_pymt_amt) > 2000”包括每个 sched_pymt_amt 而不仅仅是最新的 sched_pymt_amt_eff_dt。如何仅使用最新的 sched_pymt_amt_eff_dt 将结果限制为 sched_pymt_amt > 2000?
select person_id, sum(sched_pymt_amt) as total_pay_amt
from(
select p.person_id, lp.loan_id, lp.sched_pymt_amt, lp.sched_pymt_amt_eff_dt,
row_number() over (partition by l.loan_id order by sched_pymt_amt_eff_dt desc) rn
FROM
person p INNER JOIN
loan_dtl l on p.person_id = l.brwr_person_id INNER JOIN
loan_repymt_plan lp ON l.loan_id = lp.loan_id
where 1=1
) a
where rn=1
having sum(sched_pymt_amt) > 2000 --this is the problem line
group by person_id
您是否尝试过将
sum(sched_pymt_amt)
移至子查询?