union和union all用法


工作中,遇到同事之前寫的oracle語句中有一個union all,並且很多地方都用到了。便在網上查了一下用法,以下是自己的理解。

union  (聯合)將兩個或者多個結果集合並。

在使用時,兩個結果集要有相同的列,並且字段類型需要一致。

select id,name from tableA
union all
select name from tableB

消息 205,級別 16,狀態 1,第 1 行
使用 UNION、INTERSECT 或 EXCEPT 運算符合並的所有查詢必須在其目標列表中有相同數目的表達式。

union 和union all 的區別;

union會去除結果集中重復的部分,相當於進行一個distinct(去重),並且union 會自帶排序功能;

union all 會不管是否重復,都會將結果合並在一起輸出,沒有排序功能,只是結果集的堆疊輸出。

tableA

id  name  score

1   a    80

2     b    79

3     c      68

tableB

id  name  score

1     d    48

2   e    23

3   c    86

使用union

1、                    結果如下:name

select name from tableA                a

union                         b

select name from tableB                c

                             d

                           e

 

我們運行

select id,name from tableA

union

select id,name from tableB

結果如下:

id name

1 a
1 d
2 b
2 e
3 c

兩個表中都有 3 c ,使用union時只輸出一次。

並且我們會發現,union會按照第一列進行默認排序。

使用union all

1、

select name from tableA
union all
select name from tableB

結果:

name

a
b
c
d
e
c

2、

select id,name from tableA
union all
select id,name from tableB

結果如下:

id name

1 a
2 b
3 c
1 d
2 e
3 c

從結果看到,兩個union all 結果差別只是在於是否輸出id 其輸出順序,為 tableA所有記錄緊接tableB所有記錄,因此說union all非排序輸出。

上邊的用法應該在很多地方都可以查到吧。

下面說一下我遇到的問題。

在業務中需要查詢兩列,兩個不同的列從兩個表中獲取。

select
t.d day_id,
sum(t.OWN_COST) own_cost,
sum(t.cishu) cishu
from 
(
    select 
    to_char(f.riqi,'yyyy-mm-dd')d ,
    sum(nvl(f.feiyong1, 0))
    + sum(nvl(f.feiyong2, 0)) OWN_COST,--金額
    0  cishu
    from tablea t ,tableb f
    where 
    t.liushuihao=f.liushuihao 

    group by to_char(f.ji_fei_rq ,'yyyy-mm-dd')
 
    union all
     
    SELECT 
    to_char(jiaoyiriqi  ,'yyyy-mm-dd') d,
    0 OWN_COST,
    COUNT(case
    when JIAO_YI_LX = 1 then --【交易類型,1正交易,2反交易】
    1
    end) - COUNT(case
    when JIAO_YI_LX = 2 then --【交易類型,1正交易,2反交易】
    1
    end) cishu  
    FROM tablea 
     
    group by to_char(jiaoyiriqi,'yyyy-mm-dd')
 )t
 group by t.d

以上代碼看到兩個子查詢中都有次數和金額。當子查詢計算金額的時候,設置默認的此時為0    (0 次數);當計算次數的時候,設置金額為0 (0 own_cost)。

這樣寫的好處:

 1、當次數有問題時,我們只需要查看計算次數的子查詢部分,同理,金額錯誤時我們只需要查看相關代碼就可以。

   2、在子查詢中,設置不進行計算的值為0,對於運算結果並不會產生影響。

 

以上是本人對union的淺顯理解,歡迎各位大神指導。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM