简体   繁体   中英

How do I find mode of a column of type string in mysql?

I have a table of 2 columns, user_id and connection_type. Both the fields are not unique. One single user id can appear many times and one single connection type can appear many times. How will I find the most repeated connection_type against each user_id?

Table I have:

schema: 
user_id -- INT 
connection_type -- STRING

user_id connection_type 
101     4g 
102     3g 
101     4g 
101     2g 
102     2g 
101     4g 
102     4g 
101     4g 
102     4g 
101     4g
102     3g
102     3g
102     3g

Table I need from the above:

user_id mode 
101     4g
102     3g

You can use window function:

select user_id, connection_type as mode
from (select user_id, connection_type, 
             dense_rank() over (partition by user_id order by count(*) desc) as seq
      from table t
      group by user_id, connection_type
     ) t
where seq = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM