Postgresql – Finding two most recent payments for every sale

postgresql

Trying to get the two most recent payments for each sale number from a table of transactions (ARTRANS). Seems like a lateral join would work or maybe a window function.

Structure is fairly simple with ARTRANSID (the PK), SALENO, PAIDDATE, DUEDATE, ACCTNO (more, really, but what does that matter). Of course, with the lateral join, I'd really be doing a self join. Any suggestions on this code?

An aside: It would be cool if there were something like a GROUPLIMIT keyword, so you could limit the returned records to a certain number within the grouping. That would make this easy as pie.

Best Answer

A nice windowing function will do the job.

with phillovesCTEs as (
  select ARTRANSID, SALENO, PAIDDATE, DUEDATE, ACCTNO, 
         ROW_NUMBER() over (
                            group by SALENO 
                            order by PAIDDATE desc
                           ) as RN
  from ARTRANS 
)
select *
from phillovesCTEs
where RN <=2;