以下获取表中的所有组合:
select t1, t2, t3, t4, count(*)
from (select code, max(t1) as t1, max(t2) as t2, max(t3) as t3, max(t4) as t4
from ((select code, 1 as t1, 0 as t2, 0 as t3, 0 as t4
from table1
) union all
(select code, 0 as t1, 1 as t2, 0 as t3, 0 as t4
from table2
) union all
(select code, 0 as t1, 0 as t2, 1 as t3, 0 as t4
from table3
) union all
(select code, 0 as t1, 0 as t2, 0 as t3, 1 as t4
from table4
)
) t
group by code
) t
group by t1, t2, t3, t4;
对于您的特定问题,您可以使用:
with t as (
select code, 'table1' as tablename from table1 union all
select code, 'table2' as tablename from table2 union all
select code, 'table3' as tablename from table3 union all
select code, 'table4' as tablename from table4
)
select t1.tablename,
sum(case when t2.tablename = 'table1' then 1 else 0 end) as t1,
sum(case when t2.tablename = 'table2' then 1 else 0 end) as t2,
sum(case when t2.tablename = 'table3' then 1 else 0 end) as t3,
sum(case when t2.tablename = 'table4' then 1 else 0 end) as t4
from t t1 join
t t2
on t1.code = t2.code
group by t1.tablename
请注意,以上假设code在表中是唯一的。如果重复,可以替换union all为union.