Separate Rows by group and their percentage of total

Asked

Viewed 393 times

2

I need to get the top 10 results that appear in my table and their respective percentages by groups. For example the table:

+-----+-----+
|id   |fruit|
+-----+-----+
|  1  | or  |
|  2  | ban |
|  3  | or  |
|  4  | or  |
+-----+-----+

he would have to return me something like:

+-----+-----+-----+
|COUNT|fruit|PERCE|
+-----+-----+-----+
|  3  | or  | 90% |
|  1  | ban | 10% |
+-----+-----+-----+

90% because it represents 90% of the total Rows and so on

1 answer

3


You need to tell everything, group by fruit and sort by the count of each group, limiting to 10. Thus:

select count(id) as contagem, fruit, 
    concat(format((count(fruit) * 100 / (select count(*) from tabela)), 0), '%') as percentagem
from tabela
group by fruit desc
limit 10

I put in the Github for future reference.

  • He would also have to return the name of the fruit

  • Sure, I forgot, but this is the easy part, you’re already getting the hang of adapting these things. Anyway I edited.

  • It would be wrong to ask for more help?

  • It depends on whether you are directly relating or not. Try your luck. If it’s a good thing and you didn’t have any other answers, then you could edit it to make the question complete. But it is always important to make edits that do not invalidate answers already posted. This is why it is important to think carefully before asking to include all that is needed.

  • I made the change...

  • @user3163662 I notice that you don’t often accept the answers. Is it because they don’t answer your question or because you forget? If you forget, it would be nice to review the questions you have already asked and see if you should accept any answers. This is important for the community.

  • I lose, I function differently, when I am working on a project I think about my possible future doubts and already put them for when I get in doubt can already solve it easily and with that I have several answers that help me, but lose. I’ll mark as soon as possible, thank you

Show 2 more comments

Browser other questions tagged

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