组合两个查询(子查询)

时间:2014-01-21 16:49:50

标签: oracle10g

我在Oracle 10g中有2个表。

表1:

loan_id   installment
   1         500
   2         600
   3         800

表2:

loan_id   amount     date
   1        200      5/Jan/2014
   3        800      20/Jan/2014

步骤1:选择特定日期范围内的所有行。

Select * from table2 where date>a and date<b     

步骤2:从表2中选择其loan_id不在步骤1的结果集中的所有行。

Select * from table1 where loan_id NOT IN (Select loan_id from table2 where date>a and date<b )

步骤3:我还想选择那些(表2)数量少于分期付款(表2)的loan_id。

我的问题是,我们可以在单个查询中合并第2步和第3步吗?

感谢。

编辑:

以下组合查询为我提供了输出。

Select alias.loan_id from ((Select * from
transactions where date>2 and date<6)as alias) inner join loansapproved l on 
alias.loan_id = l.loan_id where alias.amount<l.installment
UNION 
Select l.loan_id from loansapproved l left join transactions t
on l.loan_id=t.loan_id where l.loan_id not in(Select loan_id from
transactions where date>2 and date<6) ;

有人可以简化这个吗?

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

Select t1.loan_id from table1 t1 inner join table2 t2 on t1.loan_id=t2.loan_id where t2.amount<t1.installment
and t2.date<a and t2.date>b