对子查询进行数学运算的一些问题

时间:2014-09-06 16:03:01

标签: mysql sql

是的,我正在尝试使用从子查询中检索的两个值来获取百分比。问题是,每次我这样做,我都会得到每列5000的相同值。

select *, 
       sum(100*(totalwon / (total / 100))) as percentage 
from
    (SELECT *, count(winnername) + count(losername) as total, count(winnername) as totalwon 
     FROM versus group by winnername) q1
group by 
   winnername

表格,而不是这样:

ID |  WINNERNAME   | LOSERNAME

如果我做了totalwon + total,它会将所有内容正确地汇总到一个单独的列中 - 为什么会这样?

哦,抱歉没有正确格式化消息,没有任何指示可以做到这一点。

这是一个更广泛的方式:

ID | WINNERNAME |LOSERNAME | TOTAL | TOTALWON |PERCENTAGE
1    player 1   | Player 2 | 16    |   8      | 5000
2  | player 3   | player 4 | 8     |   6      | 5000
3  | player 4   | player 6 | 4     |   4      | 5000

这就是上面的查询给我的。 但是,如果我将它从百分比计算更改为这两列之间的总和,它就可以正常工作:

ID | WINNERNAME |LOSERNAME | TOTAL | TOTALWON | Sum
1    player 1   | Player 2 | 16    |   8      | 24    #Obviously there's 16 total occurences with player 1 as the winner, therefore total = 16
2  | player 3   | player 4 | 8     |   6      | 14
3  | player 4   | player 6 | 4     |   4      | 8

2 个答案:

答案 0 :(得分:0)

以这种方式计算总和:

 select *, 
   (100 * sum(totalwon) / sum(total)) as percentage 
 from
    (SELECT *, count(winnername) + count(losername) as total, count(winnername) as totalwon 
      FROM versus group by winnername) q1
 group by winnername

答案 1 :(得分:0)

我认为你遇到的一个问题是计数(赢家或输家)。如果为true(或具有值),则逻辑计数将始终返回1。所以我不知道你的计数是如何实际工作的,因为你没有做与输家截然不同的事情。所以,如果一个人有10场比赛,我希望计数显示10胜10负,因为每列只有一个名字。

现在,正如所说的那样,我认为你还有另一张桌子,其中列出了可能匹配的所有可能的球员。从那以后,我会根据respectiv ename和position(win / lose)做两个单独的子查询,然后左键加入它们以获得答案。像

这样的东西
select
      P.PlayerName,
      coalesce( winners.timesWin, 0 ) as Wins,
      coalesce( losers.timesLost, 0 ) as Losses,
      case when coalesce( winners.timesWin, 0 ) 
              + coalesce( losers.timesLost, 0 ) = 0 then 0
           else coalesce( winners.timesWin, 0 ) 
              / (   coalesce( winners.timesWin, 0 ) 
                  + coalesce( losers.timesLost, 0 ) ) * 100 end as PctWins
   from
      Players p
         LEFT JOIN ( select winnerName as player,
                            count(*) as timesWin
                        from versus
                        group by winnerName ) winners
            on p.PlayerName = winners.player
         LEFT JOIN ( select loserName as player,
                            count(*) as timesLost
                        from versus
                        group by loserName ) losers
            on p.PlayerName = losers.player

通过这种方式,您可以获得所有可能的玩家。从那以后,你可能(甚至在显示的样本数据中),一些玩家永远不会赢,而一些玩家永远不会丢失。