SQL Server - Joining Two Tables Based on Latest Date

I have two tables:

       A
---------------
No.    Name
1      J.Smith
2      R.Alan
3.     D.Williams


       B
----------------------------
ID.    Date        Address    No.(FK from table A) 
1      10/03/01   blah blah   1
2      08/02/05   blah blah   2
3.     12/01/02   blah blah   3
4.     03/07/11   blah blah   1
5.     30/03/09   blah blah   2

I want to join two tables together, skipping rows with duplicate names based on the most recent date from table B. For example, if I join tables A and B together using the left inner join, I will get two rows for J Smith (based on rows 1 and 4 from table B). I would like to exclude the one who had an earlier date (row 1 from table B).

How can i do this?

EDIT:

I need to include all columns from table B.

+3
source share
4 answers

Maybe something like this:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY tblB.[No] ORDER BY tblB.[Date]) AS RowNbr,
        tblB.*
    FROM
        B AS tblB
)
SELECT
    *
FROM
    A AS tblA
    LEFT JOIN CTE
        ON tblA.No=CTE.No
        AND CTE.RowNbr=1
+1
source
WITH [max_dates] AS (
    SELECT [No], MAX([Date]) AS [Date]
    FROM [TableB]
    GROUP BY [No]
)
SELECT [a].[Name], [b].[Date]
FROM [TableA] AS [a]
JOIN [max_dates] AS [b] ON ([a].[No] = [b].[No])
ORDER BY [a].[No] ASC
+1
source
SELECT A.No 
     , A.Name
     , C.Date
     , C.Address
     , C. ...
FROM A 
LEFT JOIN
    ( SELECT Address , ... , No, Date,  ROW_NUMBER() OVER(PARTITION BY No ORDER BY Date DESC) AS row
        FROM B 
    ) C ON A.No = C.No 
WHERE C.row = 1

WHERE COALESCE(C.row, 1) = 1 [if there is no link ,and you'll get Date NULL]

edit: B

SELECT A.No 
     , A.Name
     , C.* (also row)
FROM A 
LEFT JOIN
    ( SELECT * ,  ROW_NUMBER() OVER(PARTITION BY No ORDER BY Date DESC) AS row
        FROM B 
    ) C ON A.No = C.No 
WHERE C.row = 1
0

CTE , :

 SELECT [A].Name, [B].Date
 FROM [A]
     INNER JOIN [B]
         INNER JOIN
         ( -- build a limitation on B
             SELECT No, MaxDate = Max(Date)
             FROM [B]
             GROUP BY No
         ) BLimit
            ON BLimit.No = B.No
            AND BLimit.MaxDate = B.Date
         ON B.No = A.No

BLimit acts as a limiter, allowing only the highest date to pass only for each No (FK). And all the fields from B can be used for the query, since the restriction occurs on B only using BLimit.

0
source

All Articles