Mysql 按两列分组并选择第三列的最大值

标签 mysql sql group-by aggregate-functions

我有一个表,其中包含 user_id、item_id 和交互类型作为列。交互类型可以是0、1、2、3、4或5。但是,对于某些user_id和item_id对,我们可能有多个interaction_type。例如,我们可能有:

user_id   item_id    interaction_type
2            3            1
2            3            0
2            3            5
4            1            0
5            4            4
5            4            2  

我想要的是仅在有多个时保留最大的interaction_type。所以我想要这个:

user_id   item_id    interaction_type
2            3            5
4            1            0
5            4            4

这是我为此目的编写的查询:

select user_id, item_id, max(interaction_type) as max_type
from mytable
group by user_id, item_id;

但是结果很奇怪。例如,在原始表中,我有 100000 行,interaction_type=5,但在结果表中,我只有 2000 行。这怎么可能,因为最大值将在包含 5 的每个比较之间选择 5,因此我不应该少于 5在结果表中。

最佳答案

您的查询没问题。您获得 2000 行的原因是因为您为每对唯一的值 user_iditem_id 获得一行。

如果您想查看每行的交互类型,请使用:

select user_id, item_id, max(interaction_type) as max_type,
       group_concat(distinct interaction_type) as interaction_types,
       count(*) as cnt
from mytable
group by user_id, item_id;

我突然想到您希望所有行都具有最大交互类型。如果是这样,计算最大值,然后查找与该值匹配的所有行:

select t.*
from mytable t cross join
     (select max(interaction_type) as maxit from mytable) x
     on x.maxit = t.interaction_type;

此查询不需要 group by

关于Mysql 按两列分组并选择第三列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43438257/

相关文章:

python - 如何通过mysql python将多个值(列表)插入数据库

.net - 针对 SQL Server 2008 运行时 SqlDataReader.HasRows 是否存在错误?

sql - Excel 表 SQL 表

mysql - 在 SQL 中显示每个用户的最后一个值(快速)

sql - 我需要做一个子查询

mysql - 如何计算两次选择中的条目数?

mysql - 选择比参数更新的最旧项目

php - 试图弄清楚 MySQL 查询的作用(不是我的)

MySQL - 错误代码 1054 - where 子句中的未知列 al.article_id

MySQL 联合计数