我有一个包含5个不同列的表:
vote_1, vote_2, vote_3, vote_4 and vote_5
对于每一行,这些列包含一个名称,我现在要做的是获取上述任何列中每个值的总出现次数。
最终结果应该是:
Value1 | 30
Value2 | 25
.....
如何在单个SQL查询中实现此目的?。
答案 0 :(得分:3)
使用UNION
将多列合并为一列。然后GROUP
和COUNT
。
select vote, count(*) as cnt
from (
select vote_1 as vote from mytable
union all select vote_2 as vote from mytable
..
union all select vote_N as vote from mytable
) sub
group by vote