Reputation: 132
SQL grouping by one value in 2 columns
Source data table:
P2 P3
----------
1 2
2 1
2 3
4 1
I want a query that counts a's and b's in each column, producing something like:
num conut
-------------
1 3
2 3
3 1
4 1
Upvotes: 0
Views: 98
Reputation: 1269623
You can do this using union all
and 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;
Upvotes: 1