选择表中所有列中所有值的计数

时间:2017-05-09 16:15:50

标签: mysql sql

我想计算一个表中所有列中每个条目的频率。 例如:

col_1| col_2 | col_3 | ...
---------------------------
a    | a     |   c   | ...
c    | d     |   e   | ...
g    | d     |   c   | ...
g    | d     |   p   | ...


Expected Result:
count_1| count_2 | count_3 | ...
---------------------------
a (1)  | a (1)   |   c(2)| ...
c (1)  | d (3)   |   e(1)| ...
g (2)  |         |   p(1)| ...

1 个答案:

答案 0 :(得分:0)

我建议您将值放在单独的中,而不是将分开:

select 'col1' as which, col1, count(*) as cnt
from t
group by col1
union all
select 'col2' as which, col2, count(*) as cnt
from t
group by col2
union all
. . .

您指定的格式不是特别关键的"格式,因为每行的值实际上不是同一实体的一部分。