简体   繁体   English

在SQL查询中执行算术

[英]Performing arithmetic in SQL query

So I'm working on a script that awards "trophies" to the top 4 performers of a game. 因此,我正在编写一个脚本,该脚本将“奖杯”授予游戏的前四名。 The table logs each "grab" attempt, the user that performed it, and whether it was successful. 该表记录了每次“抓取”尝试,执行该操作的用户以及该操作是否成功。 I'd like to create a script that is able to pull the top four off of percentage of successful grabs (attempts / successes) 我想创建一个脚本,该脚本能够将成功抓取(尝试/成功)的百分比排在前四位

Is something like this possible within the query itself using mysqli? 使用mysqli在查询本身中是否可能发生这种情况?

I have successfully accomplished the code already by just looping through each table entry, but with thousands of attempts per month it just seems like a clunky way to go about it. 我仅通过遍历每个表项就已经成功地完成了代码,但是每月要进行数千次尝试,这似乎是一种笨拙的方法。

Here is an example of a row in the table, I am attempting to grab the top four based off of monthlyTries / monthlySuccessful 这是表格中某行的示例,我正在尝试从monthlyTries / monthlySuccessfulmonthlyTries monthlySuccessful

 id  userId   PetId   PalId  tries  successfulGrabs monthlyTries   MonthlySuccessful
 5   44550    84564   3967    825      268             120               37

Assuming you have a success column that's either 1 or 0 you can sum the success and divide that by count(*) which is the total # of attempts 假设您的success列为10 ,则可以对成功进行sum并除以count(*) ,这是尝试的总数

select user_id, sum(success)/count(*) percentage
from attempts a
group by user_id
order by percentage desc
limit 4

If the success column is not a 1/0 value you can use conditional aggregation 如果success列不是1/0值,则可以使用条件聚合

select user_id, sum(case when success = 'yes' then 1 else 0 end)/count(*) as percentage
from attempts a
group by user_id
order by percentage desc
limit 4

In MySQL, you can simplify the logic. 在MySQL中,您可以简化逻辑。 If success takes on the values 0 and 1: 如果success取值为0和1:

select a.user_id, avg(success) as percentage
from attempts a
group by a.user_id
order by percentage desc
limit 4;

Otherwise: 除此以外:

select a.user_id, avg(success = 'yes') as percentage
from attempts a
group by a.user_id
order by percentage desc
limit 4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM