【问题标题】:oracle 11g sql query to get data from two tables joiningoracle 11g sql查询从连接的两个表中获取数据
【发布时间】:2012-08-23 07:06:01
【问题描述】:

我有两个表 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 表中我有

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

【问题讨论】:

    标签: sql database join oracle11g


    【解决方案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')
    

    【讨论】:

    • 由于我需要在我的最终表中使用序列号,如果我使用上述逻辑,则会收到此错误。 :( ORA-02287: sequence number not allowed here 02287. 00000 - "sequence number not allowed here" *Cause: 指定的序列号(CURRVAL or NEXTVAL)在语句中不合适。*Action: 删除序列号。错误在行:86 列:29
    • 尝试将此查询用作 FROM 类的子查询。 select seq.nextval,t.* from (... above query ...) t;.Here is a good explanation
    • Valex 无法正常工作。获取 ORA-00918:列不明确定义 00918。00000 -“列不明确定义”。我认为这是由于 ACTUAL 和 ESTIMATE 表都具有 sal_id、gal_id 列。任何其他实现方式。
    • 它必须工作Here is an example。您尝试运行的查询可能是您在最终结果查询中添加了一些同名的列。将您的查询添加到问题或 cmets 中。
    【解决方案2】:

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

    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'
    

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

    【讨论】:

    • 由于我需要在我的最终表中使用序列号,如果我使用上述逻辑,则会出现此错误。 :( ORA-02287: sequence number not allowed here 02287. 00000 - "sequence number not allowed here" *Cause: 指定的序列号(CURRVAL or NEXTVAL)在语句中不合适。*操作:删除序列号。错误在行:86 列:29
    • 如果要将结果插入到新表中,请务必在插入语句中包含列列表(INSERT INTO T()。听起来您正在尝试插入将值放入序列列中。
    猜你喜欢
    • 2012-07-26
    • 2013-08-30
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多