How to show the number of Mysql repetitions?

Asked

Viewed 739 times

3

I have a bank in which are registered names and surname, I can group the results as follows:

SELECT DISTINCT * FROM usuarios GROUP BY sobrenome

So if you have 80 records repeated of the surname "Joseph" for example, obviously it groups and shows only 1 "Joseph", but I want to not only group the names, I want to count which are the 5 most repeated surnames of the table, ie, even having more than 30 repeated surnames for example, I want to show only the 5 most repeated, ie the 5 most common table surnames. Is there any way to do this directly in Mysql or need to create some script in PHP?

  • 1

    Then it would be another SQL to bring the 5 most repeated, right?

  • Exact! would be ideal another SQL to bring the 5 most repeated.

1 answer

7


Make an SQL this way. Put limit 2 at the end to make it easier to assemble the fiddle. In your case uses limit 5.

select n.sobrenome, count(*) from nomes n
group by n.sobrenome
order by count(*) desc
limit 2

SQL running on this Fiddle

Fiddle database mount code, put here to record.

create table nomes(
  id varchar(10),
  nome varchar(40),
  sobrenome varchar(40),
  endereco varchar(40));

  insert into nomes values(
    "1","ricardo","chaves","endereco ricardo");

      insert into nomes values(
    "2","daniel","chaves","endereco daniel");

      insert into nomes values(
    "3","maria","madalena","endereco maria");

      insert into nomes values(
    "4","felipe","geraldo","endereco geraldo");

      insert into nomes values(
    "5","jose","geraldo","endereco jose");

      insert into nomes values(
    "6","jose","madalena","endereco jose1");

    insert into nomes values(
    "6","Maria2","madalena","endereco maria2");

UPDATING

Taking only the current date, whereas the column date is the date of registration:

    select n.sobrenome, data, count(*) 
      from usuarios n 
     where n.date = (data atual)
  group by n.sobrenome order by count(*) 
desc limit 5
  • Very good Ricardo, helped a lot. Thank you

  • Ricardo, and if I want to show the 5 results of the most registered surnames in the current date, type, of the whole comic, João is the most repeated, but what if I want to show the repeated only of the current date? ie the 5 most common registered today? My code looks like this: select n.sobrenome, data, count(*) from usuarios n group by n.sobrenome order by count(*) desc limit 5 I tried to include the date desc no group by, but it doesn’t work, it sorts by date. has some way of fetching data only from the current date?

  • I updated my response. When that’s so it would be nice to ask another question, because in case I delay reading the comment other people will not help you, a new question will appear to all users.

  • Thanks! It worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.