我有两个表actual和estimate具有唯一列(sal_id、gal_id、amount、tax)。
在实际的表格中我有
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
现在,我需要一个最终表,它应该有实际记录的记录,如果在实际中存在但不存在SalsIdI+GalSyId映射的记录,则填充估计记录(加上金额和税项)。
在最终表格中
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查询中编写逻辑?
最佳答案
这里有一个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')
关于sql - oracle 11g sql查询从联接的两个表中获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12164932/