2

我有两个表 ACTUAL 和 ESTIMATE 具有唯一列(sal_id、gal_id、amount、tax)。

在 ACTUAL 表中,我有

actual_id, sal_id, gal_id, process_flag, amount, tax    
1          111     222     N             100     1  
2          110     223     N             200     2

在 ESTIMATE 表中,我有

estimate_id, sal_id, gal_id, process_flag, amount, tax      
3            111     222     N             50      1  
4            123     250     N             150     2 
5            212     312     Y             10      1 

现在我想要一个最终表,它应该有来自 ACTUAL 表的记录,如果 ACTUAL 中不存在 sal_id+gal_id 映射的记录但存在于 ESTIMATE 中,则填充估计记录(以及添加金额和税款)。

在 FINAL 表中

id  sal_id, gal_id, actual_id, estimate_id, total   
1   111     222     1          null         101 (since record exist in actual table for 111 222)   
2   110     223     2          null         202 (since record exist in actual table for 110 223)  
3   123     250     null       4            51  (since record not exist in actual table but estimate exist for 123 250)    

(估计为212 312组合,由于记录已经处理,无需再次处理)。

我正在使用 Oracle 11g。请帮助我在单个 sql 查询中编写逻辑?

4

2 回答 2

2

这是一个SQLFiddle 示例

select sal_id,gal_id,actual_id,null estimate_id,amount,tax from actual where process_flag='N' 
union all
select sal_id,gal_id,null actual_id,estimate_id,amount,tax from estimate where process_flag='N' and
(sal_id,gal_id) not in (select sal_id,gal_id from actual where process_flag='N')
于 2012-08-28T18:38:53.763 回答
0

这是执行此操作的一种方法,即从 Actual 中获取所有内容,然后仅在 Estimate 中获取不在 Actual 中的内容:

select a.*
from Actual a
union all
select e.*
from Estimate e
where not exists (select 1 from actual a where a.sal_id = e.sal_id and a.gal_id = e.gal_id) and
      e.process_flag = 'N'

如果您有大量数据,这可能不是最有效的方法。但它应该适用于较小的数据集。

于 2012-08-28T18:42:01.157 回答