mySQL查询给出了不准确的结果

时间:2015-04-02 00:05:02

标签: mysql

这是我目前的查询:

select baseball , const.cnt/count(*) as my_percent 
from full_db3 inner join
 (select count(*) as cnt from full_db3 where gender = 'f') const
group by baseball
order by my_percent desc limit 10;

这会产生不准确的结果。 baseball的可能值为TRUE和FALSE,它们显示在我的结果baseball列中。但是,my_percent的值全部关闭。甚至没有关闭。

如果我运行此查询(不同GROUP BY),我在my_percent中得到的值为FALSE,但结果中没有TRUE。

select baseball , const.cnt/count(*) as my_percent 
from full_db3 inner join
 (select count(*) as cnt from full_db3 where gender = 'f') const
group by const.cnt
order by my_percent desc limit 10;

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

更简单的事情:

select baseball , 
      (sum(case when gender = 'f' then 1 else 0 end) / count(*)) * 100 as pct
FROM full_db3
group by baseball;

此查询提供了作为玩家/非玩家的女性百分比;

select gender, 
   (sum(baseball) / count(baseball)) * 100 as players, 
   (1 - (sum(baseball) / count(baseball))) * 100 as non_players
    from full_db3
    where gender = 'f'
    ;

最后一个,行中有true / false,最终确定为要求:

 select baseball, 
    (count(*) / 
       (select count(gender) from full_db3 where gender = 'f')) * 100 as pct
 from full_db3 
 where gender = 'f'
 group by baseball;

小提琴:http://sqlfiddle.com/#!9/15866/6

答案 1 :(得分:0)

看起来你正试图显示打棒球的百分比。

你不想要

SELECT baseball, gender, (100.0 * COUNT(*) / const.cnt) AS my_percent
  FROM full_db3
  JOIN (SELECT COUNT(*) AS cnt FROM full_db3) CONST
 GROUP BY baseball, gender

你可能也想要。

SELECT baseball, gender, (100.0 * COUNT(*) / const.cnt) AS my_percent
  FROM full_db3
  JOIN (
     SELECT COUNT(*) AS cnt, gender
       FROM full_db3
      GROUP BY gender
       ) CONST ON full_db3.gender = CONST.gender
 GROUP BY baseball, gender

如果你想知道' m'和' f'性别分别具有棒球属性。

100.0 *将您的分数变为百分比

在这种情况下,您的LIMIT 10没有任何意义,因为您的汇总查询不包含十个不同的类别。