计算比率

时间:2014-03-06 21:13:02

标签: mysql sql

我有一张名为交换的表格,其中我有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%

2 个答案:

答案 0 :(得分:0)

SELECT siteName,gender,
, Sum( CASE WHEN gender='M' THEN 1 ELSE 0 END ) 
/ Count(*) * 100 As male_percent
FROM siteslist
#U may need to change the next two line to work correctly so first try without them
GROUP BY siteName
Order By male_percent Desc

答案 1 :(得分:0)

您也可以尝试类似

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