10

I have a table like below:

ID   Name   Department Gender
1    Crib     MA        MALE
2    Lucy     Bsc       FEMALE
3    Phil     Bcom      MALE
4    Ane      MA        FEMALE

I have 1000 row of records like this. I want to find the ratio from column Gender( MALE & FEMALE) of all students.

I need a query to perform this.

Neeraj Kumar
  • 771
  • 2
  • 16
  • 37
san_code
  • 131
  • 1
  • 1
  • 3

4 Answers4

17

SQL Fiddle

MySQL 5.5.32 Schema Setup:

CREATE TABLE table1
    (`ID` int, `Name` varchar(4), `Department` varchar(4), `Gender` varchar(6))
;

INSERT INTO table1
    (`ID`, `Name`, `Department`, `Gender`)
VALUES
    (1, 'Crib', 'MA', 'MALE'),
    (2, 'Lucy', 'Bsc', 'FEMALE'),
    (3, 'Phil', 'Bcom', 'MALE'),
    (4, 'Ane', 'MA', 'FEMALE')
;

Query 1:

SELECT sum(case when `Gender` = 'MALE' then 1 else 0 end)/count(*) as male_ratio,
       sum(case when `Gender` = 'FEMALE' then 1 else 0 end)/count(*) as female_ratio
FROM table1

Results:

| MALE_RATIO | FEMALE_RATIO |
|------------|--------------|
|        0.5 |          0.5 |
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30
  • 1
    If you want to get decimal points, adjust as follows: ```SELECT CAST(SUM(CASE WHEN `Gender` = 'MALE' THEN 1 ELSE 0 END) AS FLOAT)/CAST(COUNT(*) AS FLOAT) as male_ratio,``` – sashaboulouds Mar 18 '20 at 21:38
  • In SQL Server, to get decimal points, I needed to multiply by 1.0, like this: ```SELECT SUM(CASE WHEN `Gender` = 'MALE' THEN 1 ELSE 0 END) * 1.0 / COUNT(*) as male_ratio,```. Casting to float didn't work for me. – Kalinda Pride Apr 13 '22 at 17:41
7

Try something like this

select sum(case when gender = 'MALE' then 1 else 0 end) / count(*) * 100 as perc_male,
sum(case when gender = 'FEMALE' then 1 else 0 end) / count(*) * 100 as perc_female
from students
S. Wirth
  • 161
  • 3
  • 8
1

This should give you the actual ratio, and should work with little or no modifcation in MySQL and SQL Server. You may have to modify the cast statement a little - my MySQL is rusty, and I think it may handle that slightly differently.

SELECT 
    (CAST((SELECT COUNT(*) FROM tblName WHERE Gender='MALE') AS FLOAT) / 
     CAST((SELECT COUNT(*) FROM tblName WHERE Gender='FEMALE') AS FLOAT)) 
    AS ratioMaleFemale;
Aaron Averett
  • 896
  • 10
  • 12
1

You're pretty close:

select (select count(*) 
          from table where gender='MALE' )/count(*)*100 as percentage_male,
       (select count(*) 
          from table where gender='FEMALE' )/count(*)*100 as percentage_female 
from table;
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30
Sebri Zouhaier
  • 745
  • 7
  • 18