我有一个称为exchanges的表,其中有我需要group by的站点名称和性别并计算性别比率。

siteName  gender
 facebook   M
 Google     F
 facebook   M
 facebook   F
Google     M
 facebook   F
 Google     M

Result
 siteName  ratio
facebook    50%
 Google      33%




SELECT siteName,gender,
  (SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END)/
  COUNT(*))*100 as male_percent
FROM siteslist
GROUP BY siteName


我不确定如何计算男性人数('M');我的查询给出0%或100%

最佳答案

您也可以尝试类似

SELECT siteName,
    gender,
    (COUNT(CASE WHEN gender='M' THEN 1 END)/ COUNT(*)) * 100 as male_percent
FROM siteslist
GROUP BY siteName

10-04 13:50