Search code examples
sqldatabaseoracle-databaseoracle-sqldeveloperprimavera

Oracle SQL count same field across multiple tables


I have an oracle database that has the same name field in multiple tables. It kind of looks like this:

table1     table2     table3     table4
field      field      field      field

The common field in each table can either be 'yes', 'no', or null. I'm trying to get the value counts of all the fields in one query, but I can't figure it out. Basically I want this:

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

I have this so far, but it only really works for one table, not multiple.

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

Solution

  • You can try using 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