分组值并从数据库中获取百分比

时间:2013-09-27 10:30:02

标签: php mysql sql database percentage

我有一个数据库表,我保存玩家按以下逻辑下注:

enter image description here

对于每个 match_id ,此表当然会有几个 user_id 。我想展示用户如何下注。如果他们认为主队将赢或输。我希望以百分比表示。

  

德国 - 法国35% - 20% - 45%。

到目前为止,我已设法使用以下查询计算数量猜测,但不计算百分比:

SELECT games.home_team,games.away_team,COUNT(*) as 'qty',user_result_bet.match_id,(
CASE
WHEN `home_score` > `away_score` THEN 'home'
WHEN `home_score` < `away_score` THEN 'away'
ELSE 'draw'
END) as 'tipped_result'
FROM user_result_bet,GAMES
WHERE games.match_id = user_result_bet.match_id
GROUP BY tipped_result, match_id
ORDER BY match_id

我从哪里开始?我想以某种方式把它变成百分比?我在网站上使用PHP

2 个答案:

答案 0 :(得分:1)

如果

,你需要使用计数
SELECT user_result_bet.match_id,COUNT(*) as 'qty',

count(if(`home_score` > `away_score`,1,null))/count(*)*100 as home_percent,
count(if(`home_score` < `away_score`,1,null))/count(*)*100 as away_percent,
count(if(`home_score` = `away_score`,1,null))/count(*)*100 as draw_percent
from wherever
group by 1

答案 1 :(得分:0)

SUM(CASE WHEN `home_score` > `away_score` THEN 1 ELSE 0 END)/COUNT(*) AS PercentageHome