我有一个表爱好:
+++++++++++++++++++++++++++++++
+ hobby_1 | hobby_2 | hobby_3 +
+---------+---------+---------+
+ music | soccer | [null] +
+ movies | music | cars +
+ cats | dogs | music +
+++++++++++++++++++++++++++++++
我想获得最常用的价值。答案是music
我知道查询以获得一列的最常值:
SELECT hobby_1, COUNT(*) FROM hobbies
GROUP BY hobby_1
ORDER BY count(*) DESC;
但是如何在组合所有列时获得最常见的值。
答案 0 :(得分:3)
您需要取消数据。这是一种方法:
select h.hobby, count(*)
from ((select hobby_1 as hobby from hobbies) union all
(select hobby_2 as hobby from hobbies) union all
(select hobby_3 as hobby from hobbies)
) h
group by h.hobby
order by count(*) desc;
但是,您应该真正修复您的数据结构。具有仅由数字区分的多个列通常是数据结构问题的标志。每个爱好都应该有一行表。