2014-01-21 114 views
0

我在Oracle 10g中有兩個表。結合兩個查詢(子查詢)

表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 

第一步:選擇特定的日期範圍之內的所有的行。

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) 

第三步:我也想選擇那些loan_id,其數量(表2)小於分期付款(表2)。

我的問題可以我們結合步驟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) ; 

任何人都可以簡化這個嗎?

+0

據我理解你的問題,你可以做到這一點。你嘗試使用連接嗎?類似如下:從table1中選擇t1.loan_id t1在t1.loan_id = t2.loan_id中將左連接table2 t2在其中t1.loan_id NOT IN(從table2中選擇loan_id,其中date> a和date Gayathri

+0

這不會將表2中的loan_ids提取出來,其金額小於分期付款。 – ArunKumar

回答

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

但左連接從左表中獲取所有貸款ID條目。 – ArunKumar

+0

好的。在這種情況下你可以使用內連接。 – Gayathri

+0

檢查sqlFiddle - > http://sqlfiddle.com/#!4/f5123/6,讓我知道如果這是你在找什麼。 – Gayathri