gpt4 book ai didi

MySql 获取一个ID的总数

转载 作者:行者123 更新时间:2023-11-29 02:25:10 25 4
gpt4 key购买 nike

抱歉,标题不太清楚。

我有包含列的表格,

ID, p1_ID, p2_ID, winner

我想在其中找到使用单个查询的获胜百分比。

我可以通过以下查询获得用户的总获胜次数,我也尝试获得总次数,但它返回 null,

SELECT count(winner) as ranking, winner, @togal_games 
FROM `gscore`, (select count(*) from `gscore` where p1_ID= winner or p2_ID = winner) as togal_games
group by winner
order by ranking desc

结果:

5   234234  NULL
3 453453 NULL
1 345344 NULL

有人可以确定如何解决或在哪里改进我的 sql 查询吗?

编辑:添加示例数据

ID  P1_ID   P2_ID   WINNER
1 234234 345344 234234
2 234234 345344 345344
3 234234 453453 234234
4 123123 234234 234234
5 234234 123123 234234
6 453453 345344 453453
7 345344 234234 234234
8 234234 453453 453453
9 453453 234234 453453

谢谢。

最佳答案

根据您的示例数据集,您可以这样做

select pid ,count(id) total_played,
sum(pid= WINNER) `wins`,
(sum(pid= WINNER) / count(id)) * 100 percent
from (
select `ID`, `P1_ID` pID, `WINNER` from t
union all
select `ID`, `P2_ID` pID, `WINNER` from t
) tt
group by pID
order by total_played DESC

Demo

您可以使用 union all 将所有玩家放在一列中,就像我在上面所做的那样,然后您可以按玩家对查询进行分组,这样 count(id)将为您提供每个玩家的比赛计数,我在 mysql 中通过 sum(pid= WINNER) 计算了获胜比赛,如果您在 sum 函数中使用任何表达式,这将导致 bool 值,所以我们得到通过将玩家 ID 与获胜者列进行比较,计算每个用户赢得的比赛数,最后一部分我计算了百分比

关于MySql 获取一个ID的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23719156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com