MySQL计算百分比

时间:2013-04-01 15:53:32

标签: mysql percentage

我有一个包含4个项目的MySQL数据库:id(数字),group_nameemployeessurveys

在我的SELECT中,我需要计算“员工”的百分比,按“调查”中的数字进行调查。

这是我现在的声明:

SELECT
  group_name,
  employees,
  surveys,
  COUNT( surveys ) AS test1, 
  ((COUNT( * ) / ( SELECT COUNT( * ) FROM a_test)) * 100 ) AS percentage
FROM
  a_test
GROUP BY
  employees

以下是表格:

INSERT INTO a_test (id, group_name, employees, surveys) VALUES
(1, 'Awesome Group A', '100', '0'),
(2, 'Awesome Group B', '200', '190'),
(3, 'Awesome Group C', '300', '290');

我很想按照employees中的数字来计算surveys的百分比。即如上面的数据所示,Awesome Group A为0%,Awesome Group B为95%。

1 个答案:

答案 0 :(得分:55)

试试这个

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE