Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select the most recent record for each ID

I have two tables, the first one is like this:

     INTERNSHIP
ID|  Term
---------
1 | 2015
1 | 2014
2 | 2016
2 | 2017

The second one is like this:

       Term
Term| Term Description | End Date
---------------------------------
2014 |  Summer 2014   | 8/12014
2014 |  Summer 2014   | 8/12014
2015 |  Fall 2015     | 12/1/2015
2017 |  Spring 2017   | 4/1/2017
2017 |  Spring 2017   | 6/1/2017

I need to find the "Term Description" for the most recent term for all the IDs. The desired result is like this:

ID| Term | Term Description 
------------------
1 |  2015   |  Fall 2015   
2 |  2017   |  Spring 2017

I did some research and came up with a solution like this:

SELECT INTERNSHIP.ID, INTERNSHIP.Term
FROM INTERNSHIP
WHERE (
  SELECT MAX(INTERNSHIP.Term)
  )
GROUP BY INTERNSHIP.ID

By that I got the distinct IDs with the most recent term, but I could not JOIN that with the Term Description. Can someone help me to get the desired result?

like image 360
Di Tran Avatar asked Jan 28 '23 02:01

Di Tran


2 Answers

TRY THIS:

SELECT i.id, i.term, t.Term_Description
FROM INTERNSHIP i
INNER JOIN Term t ON t.Term = i.term
INNER JOIN (
            SELECT MAX(t.End_Date) End_Date
            FROM INTERNSHIP i
            INNER JOIN Term t ON t.Term = i.term
            GROUP BY i.ID) t1 ON t1.End_Date = t.End_Date
like image 154
Susang Avatar answered Feb 01 '23 00:02

Susang


Does your SQL version allow you to use window functions?

If so, you can solve it easily like this :

SELECT C.ID,C.Term,C.Term_Description
FROM(
SELECT A.ID,A.TERM,B.Term_Description,Max(A.Term) OVER (PARTITION BY A.ID) AS Most_Recent_Year
FROM INTERNSHIP A INNER JOIN TERM B ON A.Term = B.Term
)C
WHERE C.Term = C.Most_Recent_Year
like image 31
Rohan Ds Avatar answered Jan 31 '23 22:01

Rohan Ds