簡體   English   中英

有沒有一種方法可以根據特定條件將兩個聯合查詢合並為一個查詢?

[英]Is there a way to combine two union queries into one single query based on particular conditions?

我有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年的關閉狀態。 所以我的問題是,我們是否可以在一個查詢中編寫此查詢,以獲取所有開放狀態以及最近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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM