2012-08-28 74 views
2

我有两个表ACTUAL AND ESTIMATE具有唯一列(sal_id,gal_id,金额,税金)。oracle 11g sql查询从两个表中获取数据

在实际的表我有

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

在评估表我有

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 

现在,我要为sal_id +最后的表,它应该有记录,从实际的表,如果没有记录存在ACTUAL中的gal_id映射,但存在于ESTIMATE中,然后填充估算记录(以及额外金额和税额)。

在最后的表

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查询中编写逻辑?

回答

1

这里是一个SQLFiddle example

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') 
+0

由于我需要在我的最终表中使用序列号,如果我使用上述逻辑,出现此错误。 :( ORA-02287:序列号这里不允许 02287. 00000 - “序列号这里不允许” *原因:指定的序列号(CURRVAL或NEXTVAL)是不合适的 在这里声明 *操作:删除 Error at Line:86 Column:29 –

+0

尝试使用此查询作为FROM类的子查询语句select select seq.nextval,t。* from(... above query ...)t;'。 [这是一个很好的解释](http://oraclequirks.blogspot.com/2008/09/ora-02287-sequence-number-not-allowed.html) – valex

+0

它不工作Valex。获取ORA-00918:列不明确定义00918. 00000 - “列定义的含糊:”我认为,这是由于其sal_id双方实际及估算表,gal_id柱实现它的任何其他方式 –

0

这里是要做到这一点,采取一切从实际然后估算只是事情是不实际的一种方式:

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' 

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

+0

由于我需要在我的决赛桌中使用序列号,如果我使用上面的逻辑,得到这个错误。 :(ORA-02287:序列号这里不允许02287. 00000 - “这里不允许序列号” *原因:。指定的序列号(CURRVAL或NEXTVAL)在声明中不恰当的位置*操作:删除序列号错误在行:86列:29 –

+0

如果要插入的结果到一个新表,一定要包括在INSERT语句中的列(INSERT INTO T中的列表()这听起来像你正试图插入值。进入序列栏 –

+0

使用这种方法选择查询本身不起作用 –

相关问题