Oracle SQL在多个表中对同一字段进行计数

问题描述

我有一个在多个表中具有相同名称字段的oracle数据库。看起来像这样:

table1     table2     table3     table4
field      field      field      field

每个表中的公共字段可以是“是”,“否”或null。我试图在一个查询获取所有字段的值计数,但我无法弄清楚。基本上我想要这个:

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  

解决方法

您可以尝试使用加入

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,1,0 from table2) union all
      (select field,0 from table3) union all
      (select field,1 from table4) 
     ) t
group by field;

与使用left join s相比,这具有三个优点:

  1. 所有字段值都包括在结果中,而不仅仅是第一张表中的值。
  2. NULL值包含在结果中。
  3. 0值包括在适当的位置(而不是NULL个计数)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...