How do I calculate ratios in SQL?

前端 未结 2 1667
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 08:48

Suppose I have a GAME table with the following fields

user_id, result

I wish to calculate win percentage defined as total numb

相关标签:
2条回答
  • 2021-01-03 09:10

    In MySQL, you can use this shortcut:

    SELECT user_id, avg(Result = 'Win') AS WinPercent
    FROM Game
    GROUP BY user_id
    ORDER BY WinPercent DESC
    

    Assuming Result is never NULL (empty string is ok). Otherwise you have to use Result IS NOT NULL AND Result = 'Win'

    0 讨论(0)
  • 2021-01-03 09:13

    Most database systems should be able to handle this with something akin to:

    Select user_id
        , Sum( Case When Result = 'Win' Then 1 Else 0 End ) / Count(*) * 1.0 As WinPercent
    From Game
    Group By user_id
    Order By WinPercent Desc
    

    Btw, I'm assuming you meant to say the win percentage is the total number of wins out of the total number of games. If you really did mean where result <> '', then you would need to modify the query like so:

    Select user_id
        , Sum( Case When Result = 'Win' Then 1 Else 0 End ) 
            / Sum( Case When Result <> '' Then 1 Else 0 End ) * 1.0 As WinPercent
    From Game
    Group By user_id
    Order By WinPercent Desc
    

    Addition

    It was suggested in comments that this is SQL Server specific. It is not. Everything in the above solutions is part of the SQL standard. Whether a given database system implements all of the features required is obviously another matter. So, if we are switching gears to finding a solution that would actually work on most database systems, the one feature that has the most variance in support would likely be the use of the column alias in the Order By. You can achieve the equivalent in a couple of ways but one way that would work on most database systems would be to use a derived table:

    Select Z.user_id, Z.WinPercent
    From    (
            Select user_id
                , Sum( Case When Result = 'Win' Then 1 Else 0 End ) 
                    / Sum( Case When Result <> '' Then 1 Else 0 End ) * 1.0 As WinPercent
            From Game
            Group By user_id
            ) As Z
    Order By Z.WinPercent Desc
    
    0 讨论(0)
提交回复
热议问题