计算组数百分比(*)

时间:2012-01-07 09:21:26

标签: mysql sql

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

如何获得给定格式的百分比值;

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

请分享SQL查询?

4 个答案:

答案 0 :(得分:10)

这是其他一些答案的略显性感版本 - 请注意使用sum(100)来避免更长时间(更平凡)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

答案 1 :(得分:2)

此查询(未经测试)应该有效:

SELECT Name,
COUNT(*) AS Count,
(COUNT(*) / _total ) * 100 AS Percentege
FROM Namelist,
(SELECT COUNT(*) AS _total
  FROM Namelist) AS myTotal
GROUP BY Name;

答案 2 :(得分:1)

替换列名并尝试:

SELECT  iName, 
    COUNT(iName) AS `Count`, 
    concat(FORMAT(((COUNT(iName) * 100) / NewPeople.iCount),2),'%') AS `Percentage`
FROM   people, (SELECT COUNT(iName) AS iCount FROM people) NewPeople 
GROUP BY iName;

输出:

Name   Count   Percentage
Sathish  5     50.00%
Jana     3     30.00%
Bala     2     20.00%

答案 3 :(得分:1)

select
name,
count(name) as `count`,
count(name)/(select count(*) from namelist)*100 as pct
from namelist
group by name