简体   繁体   中英

ORACLE SQL query from 3 tables using a latest date conditional

Hello I have this SQL statement here that queries information from 3 tables:

SELECT TABLE1.ID, TABLE2.DATE, TABLE2.VALUE, TABLE3.DESC
FROM TABLE2
LEFT JOIN TABLE1 ON TABLE2.ID = TABLE1.ID
LEFT JOIN TABLE3 ON TABLE2.ID = TABLE3.ID
WHERE TABLE1.TYPE = 1

There are times that the column ID will repeat in the resulting table.

+------+-------+---------+----------------------------+
| id   | date  | value   |  desc                      |
+------+-------+---------+----------------------------+
| 2    | 5/26  | ...     | ....                       |
| 2    | 5/27  | ...     | ....                       |
| 1    | 4/28  | ...     | ....                       |
| 1    | 3/21  | ...     | ....                       |
+------+-------+--------------------------------------+

I wanted to know how can I fix my statement so that only the latest (most recent) date for each ID would show up.

The resulting table should look like these

+------+-------+---------+----------------------------+
| id   | date  | value   |  desc                      |
+------+-------+---------+----------------------------+
| 2    | 5/27  | ...     | ....                       |
| 1    | 4/28  | ...     | ....                       |
+------+-------+--------------------------------------+

ID = 2 has 2 dates but 5/28 is the latest date so it gets retained while ID = 1 latest date is 3/21 and gets retained as well

I'm using oracle sql

Your first left join is superfluous, because the where clause turns it into an inner join.

I think the following does what you want:

SELECT TABLE1.ID, t2.DATE, t2.VALUE, TABLE3.DESC
FROM TABLE1 JOIN
     (SELECT t2.*,
             ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE DESC) as seqnum
      FROM TABLE2 t2
     ) t2
     ON t2.ID = TABLE1.ID LEFT JOIN
     TABLE3
     ON t2.ID = TABLE3.ID
WHERE TABLE1.TYPE = 1 AND seqnum = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM