9

以下查询返回许多具有相同姓名且性别 = 男性的人。

select  lookup_name.firstname,count(lookup_name.firstname)
from lookup_name
where gender='M'
group by firstname

同样,下面的查询返回许多同名且性别 = 女性的人。

select  lookup_name.firstname,count(lookup_name.firstname)
from lookup_name
where gender='F'
group by firstname

我需要编写一个查询来找出名字并告诉性别(无论是男性还是女性),数量更多。即数据库中该名称的较高概率是男性还是女性?

4

1 回答 1

10
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;
于 2012-12-11T10:11:14.620 回答