簡體   English   中英

Oracle SQL 跨多個表計算相同的字段

[英]Oracle SQL count same field across multiple tables

我有一個 oracle 數據庫,它在多個表中具有相同的名稱字段。 它看起來像這樣:

table1     table2     table3     table4
field      field      field      field

每個表中的公共字段可以是“是”、“否”或空值。 我試圖在一個查詢中獲取所有字段的值計數,但我無法弄清楚。 基本上我想要這個:

field     table1_cnt     table2_cnt     table3_cnt     table4_cnt
yes       20             25             30             35
no        35             25             15             5
null      8              6              7              5

到目前為止我有這個,但它只適用於一張桌子,而不是多張桌子。

select field, count(*) as table1_cnt
from table1
group by field
_____________________________________
field     table1_cnt
yes       20
no        35
null      8  

您可以嘗試使用 join

select t1.field,table1_cnt,table2_cnt,table3_cnt,table4_cnt
from
(
select field, count(*) as table1_cnt
from table1
group by field
)t1 left join 
(
select field, count(*) as table2_cnt
from table2
group by field
)t2 on t1.field=t2.field left join
(
select field, count(*) as table3_cnt
from table3
group by field
)t3 on t1.field=t3.field left join
(
select field, count(*) as table4_cnt
from table4
group by field
)t2 on t1.field=t4.field

我想我會建議使用union all和聚合:

select field,
       sum(table_1), sum(table_2), sum(table_3), sum(table_4)
from ((select field, 1 as table_1, 0 as table_2, 0 as table_3, 0 as table_4 from table1) union all
      (select field, 0, 1, 0, 0 from table2) union all
      (select field, 0, 0, 1, 0 from table3) union all
      (select field, 0, 0, 0, 1 from table4) 
     ) t
group by field;

與使用left join相比,這具有三個優點:

  1. 結果中包含所有字段值,而不僅僅是第一個表中的值。
  2. NULL值包含在結果中。
  3. 在適當的情況下包括0值(而不是NULL計數)。

暫無
暫無

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

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