postgreSQL - 从许多列中获取最常见的值

obr*_*rob 1 sql postgresql

我有一个餐桌爱好:

+++++++++++++++++++++++++++++++
+ hobby_1 | hobby_2 | hobby_3 +
+---------+---------+---------+
+ music   | soccer  | [null]  +
+ movies  | music   | cars    +
+ cats    | dogs    | music   +
+++++++++++++++++++++++++++++++
Run Code Online (Sandbox Code Playgroud)

我想获得最常用的值。答案是music

我知道获取一列最常见值的查询:

SELECT hobby_1, COUNT(*) FROM hobbies
    GROUP BY hobby_1
    ORDER BY count(*) DESC;
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*off 5

您需要取消数据透视。这是一种方法:

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;
Run Code Online (Sandbox Code Playgroud)

但是,您确实应该修复您的数据结构。仅通过数字区分多个列通常表明数据结构存在问题。你应该有一张桌子,每项爱好都占一行。