SQL Code to Get Most Recent Dates for Each Market ID and Corresponding House IDs

Here is the code in SQL that implements the required logic:

SELECT 
    a.Market_ID, 
    b.House_ID
FROM 
    TableA a
LEFT JOIN 
    TableB b ON a.Market_ID = b.Market_ID
AND (b.Date > a.Date FROM OR b.Date < a.Date FROM)
QUALIFY 
    ROW_NUMBER() OVER (PARTITION BY a.House_ID ORDER BY 
        CASE WHEN b.Date > a.Date FROM THEN b.Date ELSE a.Date FROM END DESC) = 1
ORDER BY 
    a.Market_ID;

This SQL code will select the Market_ID and House_ID from TableA, joining it with TableB based on the condition that either the date in TableB is greater than the Date_From in TableA or less than it. The QUALIFY clause will then ensure that only the rows where the row number is equal to 1 are selected, which means that for each Market_ID, we are selecting the House_ID with the most recent date.

This SQL code takes into account all of your requirements and should produce the desired output:

+-----------+----------+
| MARKET_ID | HOUSE_ID |
+-----------+----------+
|     14023 | NULL     |
|     14050 | 223      |
|     14101 | 151      |
|     14115 | 209      |
|     15005 | 595      |
|     15212 | 600      |
|     15516 | NULL     |
+-----------+----------+

Last modified on 2024-05-20