简体   繁体   中英

How to select MAX value in field based on another field

I currently have a query (Oracle query returning results from a linked server to a SQL table) that returns results like this: -

PersonID | EncounterNo | Location
---------+-------------+-----------
123456   | 1           | London
123456   | 2           | Manchester
123456   | 3           | Glasgow
246810   | 1           | Liverpool
246810   | 2           | Newcastle
357911   | 1           | Edinburgh
357911   | 2           | Aberdeen
357911   | 3           | Dublin

I would like to select MAX value for each PersonID so the output would be: -

PersonID | EncounterNo | Location
---------+-------------+-------------
123456   | 3           | Glasgow
246810   | 2           | Newcastle
357911   | 3           | Dublin
SELECT t.*
FROM table t
INNER JOIN (
    SELECT t.PersonID, MAX(t.EncounterNo)
    FROM table t
    GROUP BY t.PersonID
) j
ON t1.PersonID = j.PersonID AND t.EncounterNo = j.EncounterNo 

There is no need to use self-join here. You can either use analytic or aggregate functions.

For example aggregate case:

select PersonID
  , Max(EncounterNo)
  , MAx(Locaction) (DENSE_RANK FIRST ORDER BY EncounterNo Desc)
from T
group by PersonID;

The trick is to apply aggregate function "max" only onto the FIRST occurence of Location within the group (ordered by EncounterNo).

Analytic case:

Select PersonID, EncounterNo, Location
from
  (
    select T.*,
       row_number() over (partition by PersonId order by EncounterNo desc) rn
    from t
  )
 where rn=1;

See more examaples here.

SELECT YT.* 
FROM YOUR_TABLE YT, (SELECT MAX(EncounterNo) MAX_No, PersonID PID 
                     FROM YOUR_TABLE 
                     GROUP BY PERSONID) AA
WHERE YT.PersonID = AA.PID AND YT.EncounterNo = AA.MAX_No;

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