首页 > 解决方案 > 将从 2 个表中选择的 Oracle 查询加入列 a 或 b

问题描述

我正在使用 Oracle 11。

我有表 ca 和表 t。

表 ca 有列 id、effective_date、othercolumn

表 t 具有列 id、effective_date、ledger_effective_date 和 value。

如何执行查询,该查询将从 table ca join 与 table t 在任一列 Effective_date 或 ledger_effective_date 中选择?

如果找不到 ca.effective_date = t.effective_date 的匹配项,那么我想找到 ca.effective_date = t.ledger_effective_date 的匹配项。

我还加入了其他列和表,ID 和生效日期是其中的 2 列。

我使用 (+) 进行外部连接。我怎么能用 (+) 做到这一点?

此查询不起作用

(ca.effective_date = T.EFFECTIVE_DATE(+) OR ca.effective_date = T.LEDGER_EFFECTIVE_DATE(+))

示例数据

ca table
id effective_date othercolumn
1  1/1/21         a
2  1/2/21         b
3  1/3/21         c 

id effective_date  ledger_effective_date  value
1  2/5/21          1/1/21                 100 
2  1/2/21          1/3/21                 200
3  3/3/21          3/4/21                 300  

想要的结果

id othercolumn  value
1  a            100
2  b            200
3  c            null

谢谢

标签: oraclejoinoracle11gleft-join

解决方案


是的,对我来说也像是外部连接。像这样(第 1 - 11 行中的示例数据;查询从第 12 行开始):

SQL> with
  2  ca (id, effective_date, othercolumn) as
  3    (select 1, date '2021-01-01', 'a' from dual union all
  4     select 2, date '2021-01-02', 'b' from dual union all
  5     select 3, date '2021-01-03', 'c' from dual
  6    ),
  7  t (id, effective_date, ledger_effective_date, value) as
  8    (select 1, date '2021-05-02', date '2021-01-01', 100 from dual union all
  9     select 2, date '2021-01-02', date '2021-03-01', 200 from dual union all
 10     select 3, date '2021-03-03', date '2021-04-03', 300 from dual
 11    )
 12  select a.id, a.othercolumn, t.value
 13  from ca a left join t on a.effective_date = t.effective_date
 14                        or a.effective_date = t.ledger_effective_date;

        ID OTHERCOLUMN          VALUE
---------- --------------- ----------
         1 a                      100
         2 b                      200
         3 c

SQL>

不过,你为什么不加入他们的ID专栏呢?这不是更好的搭配吗?


推荐阅读