We need to calculate the gender % from user table based on gender column. So lets say, out of 10 users if there are 5 male and 5 female then we can say that male percentage is 50%

Create a table using below query:

CREATE TABLE `users` (
 `name` varchar(255) DEFAULT NULL,
 `gender` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

Insert some records using below query:

insert into users values ('bishwanath', 'male'), ('robin', 'male'), ('riya', 'female'), ('joe', 'male');

Solution1:

select ((sum(case when gender = 'male' then 1 else 0 end)/count(*))*100) as male_percentage from users limit 1;

Solution2:

select (((select count(*) from users where gender = 'male')/count(*)) * 100) as male_percentage from users limit 1;

There could be more ways of doing it. This is just for reference.

My MySQL version :Β 10.0.29-MariaDB-0ubuntu0.16.04.1

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Back To Top