获得特定范围内的平均值

时间:2019-06-20 14:08:26

标签: mysql sql

首先,我有一个基于体育博彩的数据库。我有一张名为“ MATCHES”的表格(id_match / sport_id / League_id / team / quota / result)。

假设表中有以下值:

id_match | sport_id | League_id | team | quota | result
---------------------------------------------------------
   1     |    x     |  xx       | xx   |  1.4  |  W
---------------------------------------------------------
   2     |    x     |  xx       | xx   |  2.4  |  W
---------------------------------------------------------
   3     |    x     |  xx       | xx   |  2.2  |  L
---------------------------------------------------------
   4     |    x     |  xx       | xx   |  2.35 |  W
---------------------------------------------------------

我想提取按特定范围分组的配额的成功百分比,因此我正在使用的查询如下:

SELECT  AVG(IF(bet_matches.quota BETWEEN 1.01 and 1.24 and bet_matches.result='W', 100, 0)) as '1 - 1.25' ,
    AVG(IF(bet_matches.quota BETWEEN 1.25 and 1.49 and bet_matches.result='W', 100, 0)) as '1.25 - 1.50' ,
    AVG(IF(bet_matches.quota BETWEEN 1.50 and 1.74 and bet_matches.result='W', 100, 0)) as '1.50 - 1.75' ,
    AVG(IF(bet_matches.quota BETWEEN 1.75 and 1.99 and bet_matches.result='W', 100, 0)) as '1.75 - 2' ,
    AVG(IF(bet_matches.quota BETWEEN 2 and 2.49 and bet_matches.result='W', 100, 0)) as '2 - 2.50' ,
    AVG(IF(bet_matches.quota BETWEEN 2.5 and 2.99 and bet_matches.result='W', 100, 0)) as '2.50 - 3' ,
    AVG(IF(bet_matches.quota BETWEEN 3 and 4 and bet_matches.result='W', 100, 0)) as '3 - 4' ,
    AVG(IF(bet_matches.quota >3.99 and bet_matches.result='W', 100, 0)) as '4 - x' 
FROM bet_matches

问题是当配额的胜率未充分反映在结果中时出现的。每个范围的赢率显示不正确。这些是我正在生成的结果:

1 - 1.5 | 2 - 2.5 | 
-------------------
  25%   |   50%

这些是我想要获得的结果:

 1 - 1.5 | 2 - 2.5 | 
-------------------
  100%   |   66%

任何想法如何获得此结果?预先感谢。

1 个答案:

答案 0 :(得分:0)

我想你想要

SELECT  AVG( CASE WHEN bet_matches.quota NOT BETWEEN 1.01 and 1.24 THEN NULL
                  WHEN bet_matches.result = 'W' THEN 100.0
                  ELSE 0
             END) as `1 - 1.25`,
        AVG( CASE WHEN bet_matches.quota NOT BETWEEN 1.25 and 1.49 THEN NULL
                  WHEN bet_matches.result = 'W' THEN 100.0
                  ELSE 0
             END) as `11.25 - 1.50`,
      . . .
FROM bet_matches;

关键是要计算所有行的平均值。您只想根据范围条件计算比例即可。

请注意,我将IF()替换为标准CASE。并使用反引号作为列名。请勿将单引号用作标识符。它们很容易与字符串混淆。