简体   繁体   中英

SQL - Using Subquery with Aggregate Function

I'm trying to return the last time entry posted for a particular client, and the case (matter) number associated to that entry. The relationship is one client has many matters, and one matter has many time entries.

I have the code below, but it obviously returns all the matters and not just the one associated to the time entry. I understand why, but tie myself in knots when trying to correct it. Any help much appreciated.

select c.CLIENT_CODE,
       c.CLIENT_NAME,
       c.OPEN_DATE,
       mp.EMPLOYEE_NAME,
       MAX(tt.TRAN_DATE)[Last Time],
       m.MATTER_NUMBER
from HBM_CLIENT c
join HBM_MATTER m
 on m.CLIENT_UNO=c.CLIENT_UNO
left join TAT_TIME tt
 on tt.MATTER_UNO=m.MATTER_UNO
left join HBM_PERSNL mp
 on mp.EMPL_UNO=c.RESP_EMPL_UNO
where c.STATUS_CODE = 'Targ'
group by c.CLIENT_CODE,
         c.CLIENT_NAME,
         c.OPEN_DATE,
         mp.EMPLOYEE_NAME,
         m.MATTER_NUMBER
order by OPEN_DATE

One way to do this is using row_number() . I think the following will do what you want:

select c.CLIENT_CODE, c.CLIENT_NAME, c.OPEN_DATE, mp.EMPLOYEE_NAME,
       tt.TRAN_DATE as [Last Time], m.MATTER_NUMBER
from HBM_CLIENT c join
     (select m.*, tt.TRAN_DATE,
             row_number() over (partition by m.CLIENT_UNO
                                order by tt.TRAN_DATE desc
                               ) as seqnum
      from HBM_MATTER m LEFT JOIN
           TAT_TIME tt
           ON tt.MATTER_UNO = m.MATTER_UNO
     ) m
     ON m.CLIENT_UNO = c.CLIENT_UNO and seqnum = 1 left join
     HBM_PERSNL mp
     on mp.EMPL_UNO=c.RESP_EMPL_UNO
where c.STATUS_CODE = 'Targ';

I don't think you need the group by , unless the other joins create duplicates.

Completely untested but in the right direction

select 
  <whatever> 
from 
       HBM_CLIENT c
  join HBM_MATTER m on
    m.CLIENT_UNO = c.CLIENT_UNO
  join TAT_TIME tt on
    tt.MATTER_UNO = m.MATTER_UNO AND
    tt.tran_date = (
       select max(tran_date)
       from TAT_TIME 
       where matter_uno = m.matter_uno)  
where
  m.CLIENT_UNO = ? and 
  c.STATUS_CODE = 'Targ'  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM