我正在寻找一种方法来对两个不同表中的同一列进行计数。
所以我有两个表,table1和table2。它们都具有“类别”列。我想找到一种方法来计算这两个表的类别并在下面的结果中显示。
我知道如何通过
select category, count(category) as cnt from table1
group by category
order by cnt desc
select category, count(category) as cnt from table2
group by category
order by cnt desc
不确定如何将两者结合在一起。
预期结果应如下所示。请注意,表1中有一些“类别”,但表2中没有,反之亦然,例如类别c和d。
table1 table2
a 4 2
b 4 3
c 3
d 4
答案 0 :(得分:2)
一种方法是full join
:
select coalesce(t1c.category, t2c.category) as category,
t1c.t1_cnt, t2c.t2_cnt
from (select category, count(*) as t1_cnt
from table1
group by category
) t1c full join
(select category, count(*) as t2_cnt
from table2
group by category
) t2c
on t1c.category = t2c.category;
在进行join
之前,请非常小心地汇总 。