联接2个表,其中右日期是小于或等于左日期的最大日期

时间:2019-05-03 10:40:26

标签: sql oracle date join outer-join

我有2个表要加入Oracle SQL:

Table A:
DATE        VALUE
02-May-19   19.25
03-May-19   19.35
04-May-19   19.37
06-May-19   19.45
11-May-19   19.30
01-Jun-19   18.79
01-Jul-19   19.33

Table B:
DATE        VALUE
02-May-19   11.08
01-Jun-19   11.09
01-Jul-19   11.11

我可以让外部加入它们,以在日期匹配的地方引入两个值:

select a."date" as "DATE", a.value as a_value, b.value as b_value
from a 
left outer join b on b."date" = a."date"
;

DATE        A_VALUE B_VALUE
02-May-19   19.25   11.08
03-May-19   19.35   
04-May-19   19.37   
06-May-19   19.45   
11-May-19   19.30   
01-Jun-19   18.79   11.09
01-Jul-19   19.33   11.11

我想做的是在表B中不存在该日期的地方,采用b。“ date” <= a。“ date”的最佳可用b.value。像这样:

DATE        A_VALUE B_VALUE
02-May-19   19.25   11.08
03-May-19   19.35   11.08
04-May-19   19.37   11.08
06-May-19   19.45   11.08
11-May-19   19.30   11.08
01-Jun-19   18.79   11.09
01-Jul-19   19.33   11.11

3 个答案:

答案 0 :(得分:1)

也许最简单的方法是相关子查询:

function dump(storage) {
    let store = []
    for (let i = 0, l = storage.length; i < l; i++) {
        let key = storage.key(i);
        store.push({ key: key, value: storage.getItem(key) });
    }
    console.log(JSON.stringify(store))
}

function restore(storage, store, clearBefore) {
    if (clearBefore) {
        storage.clear();
    }

    for (let i = 0, l = store.length; i < l; i++) {
        let item = store[i];
        storage.setItem(item.key, item.value);
    }
}

// usage:
// 
// dump(localStorage); // manual step: copy log output to text file
// dump(sessionStorage);
//
// let contentsFromTextFile = [ ... ]; // manual step: paste from text file
// restore(localStorage, contentsFromTextFile, true);
// restore(sessionStorage, contentsFromTextFile, true);
//
//
// EXAMPLE
// -------
// Given localStorage has one entry with key "foo" and value "bar"
// And I pasted the above code into the console
//
// When I run
//    dump(localStorage)
// Then I see the log output
//    [{"key":"foo","value":"bar"}]
//
// When I run
//    restore(localStorage, [{"key":"foo2","value":"bar2"}], true);
// Then localStorage contains only one entry with key "foo2" and value "bar2"
//
// When I run
//    restore(localStorage, [{"key":"foo3","value":"bar3"}], false);
// Then localStorage contains two entries,
//   one entry with key "foo2" and value "bar2" and
//   one entry with key "foo3" and value "bar3"

答案 1 :(得分:1)

在查询中,您可以添加带有忽略空值选项的滞后函数:

select a."date"
     , a."value"
     , coalesce(b."value", lag(b."value") ignore nulls over (order by a."date")) as best_match_value
from a 
left outer join b on b."date" = a."date"
order by a."date";

答案 2 :(得分:0)

在连接条件中使用month()year()函数

select a.date, a.value, b.value 
from a 
left outer join b 
on EXTRACT(month FROM b.date)=EXTRACT(month FROM a.date) 
and EXTRACT(year FROM b.date)=EXTRACT(yearFROM a.date)