SQL Server - how to display most recent records based on dates in two tables

I have 2 tables. I want to list entries based on recent date. For example: from the following tables, I want to display ID 2 and ID 4 using a select statement. IDs 2 and 4 are the most recent based on the dates from the second table. Please help me with the request. Thank.

ID EXID PID REASON
1  1    1    XYZ
2  2    1    ABX
3  3    2    NNN
4  4    2    AAA

EXID EXDATE
1    1/1/2011
2    4/1/2011
3    3/1/2011
4    5/1/2011

      

-1


source to share


1 answer


Here you go, this should do it. Let me know if you have any questions.



SELECT
    TBL.ID,
    TBL.EXDATE
FROM
(
    SELECT
        T1.ID,
        T2.EXDATE,
        ROW_NUMBER() OVER(PARTITION BY T1.PID ORDER BY T2.EXDATE DESC) AS 'RN'
    FROM
        Table1 T1
    INNER JOIN Table2 T2
        ON T1.EXID = T2.EXID
) TBL
WHERE
    TBL.RN = 1

      

+3


source







All Articles