where子句中的动态列更改

时间:2014-09-01 16:05:02

标签: sql plsql

以下是我的源数据和目标数据。

Source
ename   eno dept
    A   1   Rcl
    A   2   Ecs

Reference
ename   eno dept    sal hike
    A   1            10 5%
    A       Ecs      20 2%

Target
ename   eno dept    sal hike
    A   1   Rcl      10 5%
    A   2   Ecs      20 2%

我必须根据参考cloumn nullability进行列比较。

为例

我的第一个记录引用ename和eno不为null,

我的病情将是

select a.ename,b.sal,b.hike
from source a, ref_table b
where a.ename=b.ename
  and a.eno=b.en0

我的ref_table ename和dept列中的第二条记录不为null,所以我的逻辑就是

select a.ename,b.sal,b.hike
from source a, ref_table b
where a.ename=b.ename
  and a.dept=b.dept

我在哪里有变化的runttim。能否根据我的要求提供有价值的解决方案。

2 个答案:

答案 0 :(得分:2)

我对你的问题有点困难,比如:

select a.ename, a.eno, a.dept, b.sal, b.hike
from source a
join ref_table b
    on a.ename = b.ename
    and a.dept = coalesce(b.dept, a.dept)
    and a.eno = coalesce(b.eno, a.eno)

答案 1 :(得分:0)

应该这么简单:

SELECT  a.ename,b.sal,b.hike
FROM source a, ref_table b
where 
(b.ename IS NOT NULL AND b.eno IS NOT NULL AND
 a.ename=b.ename AND a.eno=b.eno)
OR 
(b.ename IS NOT NULL AND b.dept IS NOT NULL AND
  a.ename=b.ename AND a.dept=b.dept)

这可以简化为:

SELECT  a.ename,b.sal,b.hike
FROM source a, ref_table b
where a.ename=b.ename
AND ((b.eno IS NOT NULL AND a.eno=b.eno)
  OR (b.dept IS NOT NULL AND a.dept=b.dept)

对于有多个可以为NULL的列的情况,请尝试使用默认值等于其他表中的值的解决方案:

SELECT  a.ename,b.sal,b.hike
FROM source a, ref_table b
WHERE a.ename = NVL(b.ename, a.ename)
 AND a.eno = NVL(b.eno, a.eno)
 AND a.dept = NVL(b.dept, a.dept)

这样,WHERE子句中将忽略NULL值。