所以我正在制作一个剧本,奖励游戏前4名表演者的“奖杯”。该表记录每次“抓取”尝试,执行该尝试的用户以及是否成功。我想创建一个能够将成功抓取百分比(尝试/成功)排在前四位的脚本
使用mysqli在查询本身中是否可以这样?
我已经成功完成了代码,只需循环遍历每个表条目,但每月有数千次尝试,这似乎是一种笨重的方式。
以下是表格中一行的示例,我尝试根据monthlyTries
/ monthlySuccessful
id userId PetId PalId tries successfulGrabs monthlyTries MonthlySuccessful
5 44550 84564 3967 825 268 120 37
答案 0 :(得分:4)
假设您有一个success
列1
或0
,您可sum
成功并将其除以count(*)
总尝试次数
select user_id, sum(success)/count(*) percentage
from attempts a
group by user_id
order by percentage desc
limit 4
如果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
答案 1 :(得分:0)
在MySQL中,您可以简化逻辑。如果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;
否则:
select a.user_id, avg(success = 'yes') as percentage
from attempts a
group by a.user_id
order by percentage desc
limit 4;