我有一张如下表:
ID Name Department Gender
1 Crib MA MALE
2 Lucy Bsc FEMALE
3 Phil Bcom MALE
4 Ane MA FEMALE
我有1000行这样的记录。我想找到所有学生的性别(男性和女性)栏目的比例。
我需要一个查询来执行此操作。
答案 0 :(得分:9)
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')
;
查询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 |
答案 1 :(得分:3)
尝试这样的事情
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
答案 2 :(得分:0)
怎么样
select gender, count(*)
from table
group by gender
然后自己计算比率非常简单。
答案 3 :(得分:0)
这应该给你实际的比例,并且应该在MySQL和SQL Server中很少或没有修改。您可能需要稍微修改一下cast语句 - 我的MySQL已经生锈了,我认为它可能会略有不同。
SELECT
(CAST((SELECT COUNT(*) FROM tblName WHERE Gender='MALE') AS FLOAT) /
CAST((SELECT COUNT(*) FROM tblName WHERE Gender='FEMALE') AS FLOAT))
AS ratioMaleFemale;
答案 4 :(得分:0)
你非常接近:
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;