D
D
delongeroman2021-02-13 21:21:39
SQL
delongeroman, 2021-02-13 21:21:39

How to display the most repeated value in a table when grouping?

Good day!
How do I deduce from this table, when grouped by age, the most recurring hobby for each age group. Here, for example, there should be 18 - fishing, 20 - football.
60281857dc8c8927536867.png
Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-02-13
@delongeroman

A bit tricky but works:

select *
from (
  select age, hobbies, count(*) cnt
  from user_hobbies
  group by age, hobbies
) age_hobbies
join (
select age, max(cnt) maxcnt
from (
  select age, hobbies, count(*) cnt
  from user_hobbies
  group by age, hobbies
) h group by age
) max_age_hobbies on 
  age_hobbies.age = max_age_hobbies.age and 
  age_hobbies.cnt = max_age_hobbies.maxcnt;

MariaDB fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question