postgreSQL - 从许多列获得最频繁的值

时间:2017-12-13 17:07:51

标签: sql postgresql

我有一个表爱好:

+++++++++++++++++++++++++++++++
+ 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;

但是如何在组合所有列时获得最常见的值。

1 个答案:

答案 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;

但是,您应该真正修复您的数据结构。具有仅由数字区分的多个列通常是数据结构问题的标志。每个爱好都应该有一行表。