Mysql group by two columns and pick the maximum value of third column

后端 未结 1 1277
醉话见心
醉话见心 2021-01-27 19:19

I have a table that has user_id, item_id and interaction_type as columns. interaction_type could be 0, 1,2,3,4 or 5. However, for some user_id and item_id pairs, we might have m

相关标签:
1条回答
  • 2021-01-27 19:42

    Your query is fine. The reason you are getting 2000 rows is because you are getting one row for every unique pair of values user_id, item_id.

    If you want to see the interaction types going into each row then use:

    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;
    

    It occurs to me that you want all rows with the maximum interaction type. If so, calculate the maximum and then find all rows that match that value:

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

    No group by is needed for this query.

    0 讨论(0)
提交回复
热议问题