MySql十进制问题输出

时间:2015-04-07 22:58:53

标签: mysql casting sum percentage

晚间

我有一个运动表,按成功百分比排序((赢得比赛+(游戏抽奖/ 2)/游戏玩法),我输出后如果100%的比赛获胜,那么它读数为1.000,75%然后是.750,50%为.500等(前导0下降)。

目前我可以让它显示0.000到0.950,如果球队只打了1场比赛并赢了,那么输出显示0.100。

我怎样才能: a)让它显示1场比赛/赢得1.000 b)显示和其他组合的百分比如.500

任何想法?

由于

SELECT team
     , COUNT(*) as played
     , SUM(win) as wins
     , SUM(loss) as lost
     , SUM(draw) as draws
     , SUM(SelfScore) as ptsfor
     , SUM(OpponentScore) as ptsagainst
     , SUM((win*2 + draw)- loss) as score
     , CAST(SUM(win + (draw/2))/(count(*)) as decimal(3,3)) pctWon
FROM (
      SELECT team
     , SelfScore
     , OpponentScore
     , SelfScore > OpponentScore win
     , SelfScore < OpponentScore loss
     , SelfScore = OpponentScore draw
      FROM (
        SELECT HomeTeam team, HomeScore SelfScore, AwayScore OpponentScore
        FROM Game
        WHERE Season = '2015' and Type = 'League'
        UNION ALL 
        SELECT AwayTeam, AwayScore, HomeScore
        FROM Game
        WHERE Season = '2015' and Type = 'League'
       ) a
) b
GROUP BY team
ORDER BY pctWon DESC, score DESC, ptsagainst DESC, team ASC;
        ");

这会生成一个正确的表格,除了前2个显示PCT不正确。

Team    W   L   T   PF  PA  PCT
T1      1   0   0   54  0   0.100
T2      1   0   0   44  0   0.100
T3      0   1   0   0   54  0.000
T4      0   1   0   0   44  0.000
T5      6   2   2   220 122 0.700
T6      7   3   0   247 139 0.700
T7      6   4   0   191 191 0.600
T8      4   5   1   167 201 0.450
T9      3   6   1   142 202 0.350
T10     2   8   0   193 305 0.200

由于

2 个答案:

答案 0 :(得分:0)

DECIMAL(3,3)在小数点左边没有空格。您需要DECIMAL(4,3)

您使用的是哪个版本的MySQL? 0.100听起来像个错误。但是我无法在5.6.12上用

重现它
mysql> SELECT CAST(((1+0/2)/1) AS DECIMAL(3,3));
+-----------------------------------+
| CAST(((1+0/2)/1) AS DECIMAL(3,3)) |
+-----------------------------------+
|                             0.999 |
+-----------------------------------+

请注意,(4,3)可以为您提供所需内容:

mysql> SELECT CAST(((1+0/2)/1) AS DECIMAL(4,3));
+-----------------------------------+
| CAST(((1+0/2)/1) AS DECIMAL(4,3)) |
+-----------------------------------+
|                             1.000 |
+-----------------------------------+

答案 1 :(得分:0)

我终于纠正了这个问题!

问题似乎是在CAST内玩的游戏的COUNT。

而不是:

 , CAST(SUM(win + (draw/2))/(count(*)) as decimal(3,3)) pctWon

以下给出了正确的输出:

 , CAST(SUM(win + (draw/2))/SUM(win + loss + draw) as decimal(4,3)) as pctWon