2016-04-15 73 views
0

我有2個表下面的格式有沒有辦法根據特定條件將兩個聯合查詢合併爲一個查詢?

 TableA        TableB 
ID1 Name Date     ID1 Status 
1 abc April 2000    1  open 
2 xyz May 2000     2  closed 
3 def March 2016    3  closed 
4 pqr March 2016    4  open 

隨着下面的查詢

SELECT a.id1, 
     a.name, 
     a.date, 
     b.status 
FROM TableA a 
JOIN TableB b ON a.id1=b.id2 
AND b.status='open' 
UNION 
SELECT a.id1, 
     a.name, 
     a.date, 
     b.status 
FROM TableA a 
JOIN TableB b ON a.id1=b.id2 
AND b.status='closed' 
AND a.date>'April 2014' 

我得到下面的結果集

a.id1 a.name a.date  b.status 
1  abc  April 2000 open 
3  def  March 2016 closed 
4  pqr  March 2016 open 

我的目的是要顯示所有打開的狀態和給定ID的最近兩年的關閉狀態。 所以我的問題是,我們可以在一個單一的查詢中寫出這個查詢來獲得所有開放和最後2年的關閉狀態嗎? 請建議。

+0

如果您的日期比較錯誤,'2014年4月'和'2016年3月'是字符串,所以字符串比較認爲'3月'>'4月'。 – lobo

回答

2

我在單個查詢中重寫了您的查詢。

select a.id1, a.name, a.date, b.status 
    from TableA a 
    join TableB b 
    on a.id1 = b.id2 
where (b.status = 'closed' and a.date > 'April 2014') 
    or b.status = 'open' 
+0

謝謝。有效。 – Naresh