如何在每个 id 组的列中选择最频繁的值? [英] How to select most frequent value in a column per each id group?

查看:11
本文介绍了如何在每个 id 组的列中选择最频繁的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 SQL 中有一个如下所示的表:

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
1       | 3
1       | 3
1       | 7

我想编写一个返回两列的查询:一列是用户 ID,另一列是每个 ID 最常出现的值.在我的示例中,对于 user_id 0,最常见的值为 6,而对于 user_id 1,最常见的值为 3.我希望它如下所示:

I want to write a query that returns two columns: a column for the user id, and a column for what the most frequently occurring value per id is. In my example, for user_id 0, the most frequent value is 6, and for user_id 1, the most frequent value is 3. I would want it to look like below:

user_id | most_frequent_value
0       | 6
1       | 3

我正在使用下面的查询来获取最常见的值,但它针对整个表运行并返回整个表而不是每个 id 的最常见值.我需要在查询中添加什么以使其返回每个 id 的最频繁值?我想我需要使用子查询,但不确定如何构建它.

I am using the query below to get the most frequent value, but it runs against the whole table and returns the most common value for the whole table instead of for each id. What would I need to add to my query to get it to return the most frequent value for each id? I am thinking I need to use a subquery, but am unsure of how to structure it.

SELECT user_id, data1 AS most_frequent_value
FROM my_table
GROUP BY user_id, data1
ORDER BY COUNT(*) DESC LIMIT 1

推荐答案

您可以使用窗口函数根据用户 ID 的 data1 计数对其进行排名.

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 

这篇关于如何在每个 id 组的列中选择最频繁的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆