如何在SQL中找到值的百分比?

时间:2012-11-03 21:22:41

标签: mysql sql database

我使用以下查询来查明Hero在游戏中获胜的百分比:

SELECT Hero, (COUNT(*) * g.games) AS p
FROM gamestatistics
JOIN (
SELECT 100/COUNT(*) AS games
FROM gamestatistics
) AS g
WHERE PointEarned>0
GROUP BY Hero
ORDER BY p DESC

但这给了我所有游戏的百分比。我想知道

  

percentage(for Hero)=(Won games by this player)/(Played games by this hero)

而不是

  

百分比(对于英雄)=(由该玩家赢得游戏)/(所有游戏)
  感谢。

3 个答案:

答案 0 :(得分:4)

SELECT  hero, AVG(pointEarned > 0) p
FROM    gamestatistics
GROUP BY
        hero
ORDER BY
        p DESC

答案 1 :(得分:2)

试试这个

select
   gc.Hero,
   sum(case when gc.PointEarned > 0 then 1 else 0 end) / count(*) as p
from gamestatistics as gc
group by by gc.Hero
order by p desc

答案 2 :(得分:1)

使用count(HERO)代替count(*),因为我认为它无法正常执行该群组。

  SELECT Hero, (COUNT(HERO) * g.games) AS p
  FROM gamestatistics
  JOIN (
        SELECT 100/COUNT(*) AS games
        FROM gamestatistics
  ) AS g
  WHERE PointEarned>0
  GROUP BY Hero
  ORDER BY p DESC;

编辑:我相信你希望sum of PointsEarned按计数划分。在这种情况下,查询几乎没有改变如下:

SELECT Hero, (SUM(case when PointEarned <1 then 0 else 1 end)*100/count(HERO)) AS p
FROM gamestatistics
GROUP BY Hero
ORDER BY p DESC;