Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

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

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you go, this ought to 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...