按2列中的一个值分组SQL
Source data table:
P2 P3
----------
1 2
2 1
2 3
4 1
我想要一个计算每列中的a和b的查询,产生类似:
num conut
-------------
1 3
2 3
3 1
4 1
答案 0 :(得分:1)
您可以使用union all
和group by
:
select num, sum(cnt) as conut
from (select p2 as num, count(*) as cnt from source group by p2
union all
select p3 as num, count(*) as cnt from source group by p3
) p
group by num;