Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation of percentage of group count(*)

Tags:

sql

mysql

Select * from Namelist;
Name      Age
Sathish   25
Sathish   65
Sathish   55
Sathish   45
Sathish   35
Jana      55
Jana      25
Jana      10
Bala      55
Bala      26

How to get Percentage value for given format;

Name   Count   Percentege
Sathish  5     50%
Jana     3     30%
Bala     2     20%

Kindly share sql query?

like image 302
Sathish Robert Avatar asked Jan 07 '12 09:01

Sathish Robert


People also ask

How do you find the percentage of a group?

Finding the percentageDivide the number that you want to turn into a percentage by the whole. In this example, you would divide 2 by 5. 2 divided by 5 = 0.4. You would then multiply 0.4 by 100 to get 40, or 40%.

How do I find the percentage of each category in SQL?

Finding Percentages between two columns is straightforward. You can simply use the column names and the division operator “/” to divide values in one column by another. The result is a list of values that correspond to the result of the division of all the values in the two columns.

How do I calculate a sample percentage?

If we have to calculate percent of a number, divide the number by the whole and multiply by 100. Hence, the percentage means, a part per hundred. The word per cent means per 100. It is represented by the symbol “%”.


2 Answers

This is a slightly sexier version of some of the other answers - note the use of sum(100) to avoid the longer (and more mundane) count(*) * 100 :)

select name, count(*) as count, sum(100) / total as percentage
from namelist
cross join (select count(*) as total from namelist) x
group by 1
like image 183
Bohemian Avatar answered Nov 03 '22 22:11

Bohemian


This query(not tested) should work :

SELECT Name,
COUNT(*) AS Count,
(COUNT(*) / _total ) * 100 AS Percentege
FROM Namelist,
(SELECT COUNT(*) AS _total
  FROM Namelist) AS myTotal
GROUP BY Name;
like image 20
aleroot Avatar answered Nov 03 '22 22:11

aleroot