30
votes

I have a MySQL database with 4 items: id (numerical), group_name, employees, and surveys.

In my SELECT I need to calculate the percentage of 'employees' who, by the number in 'surveys', have taken the survey.

This is the statement I have now:

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

Here is the table as it stands:

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');

I would love to calculate the percentage of employees who by the number in surveys have taken the survey. i.e. as shown in the data above, the Awesome Group A would be 0% and Awesome Group B would be 95%.

1
This GROUP BY practice should not be used. It is non-standard and will produce undesired results. - Kermit
sample data and your wished reslut maybe ? - echo_Me
Here is the table as it stands: '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');' I would love to calulate the percentage of 'employees' who by the number in 'surveys' have taken the survey. IE like above the Awesome Group A would be 0% and Awesome Group B would be 95% - user2232709
@Thomas MySQL chooses which fields to GROUP BY as it feels. All other platforms require that non-aggregated fields in the SELECT appear in the GROUP BY. MySQL doesn't follow this standard. - Kermit
@Thomas Just to add that it isn't the fields that it chooses as it feels, it's the value for the non-group fields which it chooses to display. In 5.8 (maybe 5.7 too) the behaviour is now consistent with other databases. The non-standard behaviour was useful but dangerous if you were relying on it. - Chris McCauley

1 Answers

78
votes

try this

   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