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

后端 未结 3 1156
[愿得一人]
[愿得一人] 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:16

    You can use a window function to rank the userids based on their count of data1.

    WITH cte AS (
    SELECT 
        user_id 
      , data1
      , ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY COUNT(data1) DESC) rn
    FROM dbo.YourTable
    GROUP BY
      user_id,
      data1)
    
    SELECT
        user_id,
        data1
    FROM cte WHERE rn = 1 
    

提交回复
热议问题