Separate rows by group and their percentage of total

2

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

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

It would have to return something like:

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

90% why it represents 90% of all rows and so goes

    
asked by anonymous 26.12.2014 / 23:40

1 answer

3

You need to count all, group by fruit and sort by counting each group, limiting by 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
    
26.12.2014 / 23:44