Mysql
 sql >> Base de données >  >> RDS >> Mysql

Comment calculer le ratio à l'aide d'une requête sql?

SQL Fiddle

Configuration du schéma MySQL 5.5.32 :

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

Requête 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

Résultats :

| MALE_RATIO | FEMALE_RATIO |
|------------|--------------|
|        0.5 |          0.5 |