以下查询会返回许多具有相同名称且性别=男性的人。
select lookup_name.firstname,count(lookup_name.firstname)
from lookup_name
where gender='M'
group by firstname
同样,下面的查询会返回一些名为gender = Female的人。
select lookup_name.firstname,count(lookup_name.firstname)
from lookup_name
where gender='F'
group by firstname
我需要编写一个查询,找出名称并告诉性别(无论男性还是女性)计数更多。即数据库中该名称的概率是男性还是女性的更高概率?
答案 0 :(得分:8)
SELECT firstname, Male, Female,
case when Male=Female then 'indeterminate'
when Male>Female then 'probably male'
else 'probably female' end MostProbablySex
FROM (
select firstname,
SUM(case when gender='M' then 1 else 0 end) Male,
SUM(case when gender='F' then 1 else 0 end) Female
from lookup_name
group by firstname
) X;
或一次通过:
select firstname,
CASE SIGN(2.0 * SUM(case when gender='M' then 1 else 0 end) / COUNT(*) - 1)
WHEN -1 then 'probably female'
WHEN 0 then 'indeterminate'
WHEN 1 then 'probably male'
END
from lookup_name
group by firstname;