SQL按2列中的一个值分组

时间:2014-11-14 13:22:53

标签: sql sql-server

按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

1 个答案:

答案 0 :(得分:1)

您可以使用union allgroup 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;