我有两张这样的table
WITH table1 AS (
SELECT TO_DATE('03/24/2015 11:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col FROM DUAL UNION ALL
SELECT TO_DATE('08/03/2016 07:15:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col FROM DUAL UNION ALL
SELECT TO_DATE('02/29/2016 22:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col FROM DUAL
),
table2 AS (
SELECT TO_DATE('03/20/2015 11:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row1' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('03/21/2015 11:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row1' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('03/25/2015 11:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row2' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('08/02/2016 07:15:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row3' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('08/04/2016 07:15:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row4' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('02/28/2016 22:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row5' AS data_col FROM DUAL UNION ALL
SELECT TO_DATE('03/01/2016 22:30:00', 'mm/dd/yyyy hh24:mi:ss') AS date_col, 'table2_row6' AS data_col FROM DUAL
)
select * from table1
字符串
如何找到表2中最小的最近日期?
2条答案
按热度按时间mwg9r5ms1#
我们可以使用简单易懂的方法:
字符串
vx6bjr1n2#
在Oracle 12中,使用
LATERAL
join和FETCH FIRST ROW ONLY
:字符串
其输出:
| 日期_COL|最早日期|DATA_COL|
| --|--|--|
| 2015-03-24 11:30:00| 2015-03-21 11:30:00|表2_row1|
| 2016-08-03 07:15:00| 2016-08-02 07:15:00|表2_row3|
| 2016-02-29 22:30:00| 2016-02-28 22:30:00|表2_row5|
如果你想要最接近的日期(更早或更晚),那么:
型
其输出:
| 日期_COL|最近日期COL| DATA_COL|
| --|--|--|
| 2015-03-24 11:30:00| 2015-03-25 11:30:00|表2_row2|
| 2016-08-03 07:15:00| 2016-08-02 07:15:00|表2_row3|
| 2016-02-29 22:30:00| 2016-02-28 22:30:00|表2_row5|
fiddle