在同一个表中的多个列中计算项目

时间:2016-05-27 08:18:30

标签: mysql sql

我的表格如下所示

表A

------------------------------------
id| ColumnA   | ColumnB   | ColumnC   
------------------------------------
1 | A        | B         | B      
2 | B        | D         | D
3 | C        | E         | A
------------------------------------

如何统计每列中每个项目的出现次数?

我想要的结果如下:

--------------------
Result    | Counter
--------------------
A         | 2
B         | 3
C         | 1
D         | 2
E         | 1

对于单列,我可以使用此SQL:

SELECT ColumnA, COUNT(*)
FROM TableA
GROUP BY ColumnA
HAVING COUNT(*) > 0

多列怎么样?任何帮助都会很棒!

2 个答案:

答案 0 :(得分:3)

试试这个;)

select c as Result, count(1) as Counter from (
    select ColumnA c from TableA
    union all
    select ColumnB c from TableA
    union all
    select ColumnC c from TableA ) t
group by c

答案 1 :(得分:1)

可以这样做:

SELECT ColumnA as Result, sum(1) as Counter FROM (
  SELECT ColumnA FROM youTable
  UNION ALL
  SELECT ColumnB FROM youTable
  UNION ALL
  SELECT ColumnC FROM youTable
) AS res
GROUP BY ColumnA;