How to select most frequent value in a column per each id group?

后端 未结 3 1164
[愿得一人]
[愿得一人] 2021-01-01 22:08

I have a table in SQL that looks like this:

user_id | data1
0       | 6
0       | 6
0       | 6
0       | 1
0       | 1
0       | 2
1       | 5
1       | 5
1         


        
3条回答
  •  半阙折子戏
    2021-01-01 22:10

    If you use proper "order by" then distinct on (user_id) make the same work because it takes 1.line from data partitioned by "user_id". DISTINCT ON is specialty of PostgreSQL.

    select distinct on (user_id) user_id, most_frequent_value from (
    SELECT user_id, data1 AS most_frequent_value, count(*) as _count
    FROM my_table
    GROUP BY user_id, data1) a
    ORDER BY user_id, _count DESC 
    

提交回复
热议问题