[英]postgreSQL - get most frequent value from many columns
I have a table hobbies: 我有一个餐桌爱好:
+++++++++++++++++++++++++++++++
+ hobby_1 | hobby_2 | hobby_3 +
+---------+---------+---------+
+ music | soccer | [null] +
+ movies | music | cars +
+ cats | dogs | music +
+++++++++++++++++++++++++++++++
I want to get to most freuqent used value. 我想获得最常用的价值。 The answer would be
music
答案将是
music
I know the query to get the most frequent value for one column: 我知道查询以获得某一列的最频繁值:
SELECT hobby_1, COUNT(*) FROM hobbies
GROUP BY hobby_1
ORDER BY count(*) DESC;
But how to get the most frequent value when combining all columns. 但是如何在组合所有列时获得最频繁的值。
You need to unpivot the data. 您需要取消数据透视。 Here is one method:
这是一种方法:
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;
However, you should really fix your data structure. 但是,您应该真正修复数据结构。 Having multiple columns only distinguished by a number is usually a sign of a problem with the data structure.
仅用数字区分多个列通常是数据结构出现问题的迹象。 You should have a table with one row for each hobby.
您应该有一张桌子,每个爱好一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.