Oracle SQL 计算多个表中的相同字段
Oracle SQL count same field across multiple tables
我有一个 oracle 数据库,在多个 table 中具有相同的名称字段。它看起来像这样:
table1 table2 table3 table4
field field field field
每个 table 中的公共字段可以是 'yes'、'no' 或 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
目前我有这个,但它只适用于一个 table,而不适用于多个。
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, 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
s 相比,这具有三个优势:
- 所有 字段值都包含在结果中,而不仅仅是第一个 table.
中的值
NULL
个值包含在结果中。
0
值包含在适当的地方(而不是 NULL
计数)。
我有一个 oracle 数据库,在多个 table 中具有相同的名称字段。它看起来像这样:
table1 table2 table3 table4
field field field field
每个 table 中的公共字段可以是 'yes'、'no' 或 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
目前我有这个,但它只适用于一个 table,而不适用于多个。
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, 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
s 相比,这具有三个优势:
- 所有 字段值都包含在结果中,而不仅仅是第一个 table. 中的值
NULL
个值包含在结果中。0
值包含在适当的地方(而不是NULL
计数)。