apartment_Table
ID | update_Date | code | address1 | address2 | city | state_code | zip_code |
---|---|---|---|---|---|---|---|
1 | 2023/02/15 | CO | Apt 320 | null | NYC | NY | 10012 |
1 | 2021/12/03 | CO | Apt 105 | null | NYC | NY | 10012 |
1 | 2023/02/15 | WK | 5th Avenue | null | NYC | NY | 10012 |
2 | 2023/02/15 | CO | Apt 325 | null | NYC | NY | 10012 |
2 | 2022/01/12 | CO | Apt 123 | null | NYC | NY | 10012 |
2 | 2023/02/14 | WK | 4th Avenue | null | NYC | NY | 10012 |
2 | 2021/02/11 | WK | 5th Avenue | null | NYC | NY | 10012 |
From the table, WK code is road_name and CO code is apartment number.
update_Date is the latest data when user update in the system. I would like to know How do I get result like below
(latest update_Date WK belong to latest update_Date CO)
ID | tenant_address |
---|---|
1 | 5th Avenue, Apt 320, NYC, NY, 10012 |
2 | 4th Avenue, Apt 325, NYC, NY, 10012 |
SQL I wrote:
SELECT
View_B_ID AS ViewID,
DECODE(P.address1, NULL, 'Street Not Available, ', SUBSTR(P.address1, 1, 50) || ', ')
|| DECODE(P.address2, NULL, '', SUBSTR(P.address2, 1, 50) || ', ')
|| DECODE(P.CITY, NULL, '', P.CITY || ', ')
|| DECODE(P.STAT_CODE, NULL, '', STAT_CODE || ', ')
|| DECODE(P.ZIP, NULL, '', P.ZIP) AS tenant_address
FROM View_B --assume I get data from View_B
LEFT JOIN (SELECT R.ID,
R.address1,
R.address2,
R.CITY,
R.STAT_CODE,
R.ZIP,
ROW_NUMBER() OVER(PARTITION BY R.ID ORDER BY R.update_Date DESC) AS RN
FROM apartment_Table R
WHERE R.code = 'CO'
) P
ON ViewID = P.ID
AND P.RN = 1
Output:
ID | tenant_address |
---|---|
1 | Apt 320, NYC, NY, 10012 |
2 | Apt 325, NYC, NY, 10012 |
Should I use LISTAGG function ? how to get the correct result ? please help. thank you so much