Search code examples
sqljoinsubquery

multiple joins to same sub query


I need to join to the same table repeatedly but this looks ugly. Any suggestions appreciated. Below is simplified SQL, I have 8 tables in the subquery and it produces many duplicate records of the same date, so I need to find only the newest record for each client. (I don't think DB and/or version should matter, but I am using DB2 11.1 LUW)

select c.client_num, a.eff_date, t.trx_date
from client c 
join address a on(a.id = c.addr_id)
join transaction t on(t.addr_id = a.id)
{many other joins}
where {many conditions};

select SQ.*
from [ABOVE_SUBQUERY] SQ
join
    (select client_num, max(eff_date) AS newest_date from [ABOVE_SUBQUERY] group by client_num) AA
    ON(SQ.client_num = AA.client_num and SQ.eff_date = AA.newest_date)
join
    (select client_num, max(trx_date) AS newest_date from [ABOVE_SUBQUERY] group by client_num) TT 
    ON(SQ.client_num = TT.client_num and SQ.trx_date = TT.newest_date)

Solution

  • I need to fine only the newest record for each client.

    Can't you just use row_number()?

    select t.*
    from (select t.*,
                 row_number() over (partition by client_num order by eff_date desc, eff_time desc) as seqnum
          from <whatever> t
         ) t
    where seqnum = 1;