gpt4 book ai didi

MySQL百分比将计数除以总和

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

我有一个表games,我有字段namegameStatuscreated_at

这是我得到的结果

| name    | total   | percentage |   
| Caleb | 13992 | 11.8372 |
| Fabian | 27570 | 23.3241 |
| Frank | 7181 | 6.0751 |
| Francis | 19897 | 16.8328 |
| Felix | 4319 | 3.6539 |
| Gary | 1 | 0.0008 |
| George | 2405 | 2.0346 |
| Gavin | 16144 | 13.6577 |
| Gab | 22076 | 18.6762 |
| Nigel | 367 | 0.3105 |
| Peter | 2465 | 2.0854 |
| Troy | 1787 | 1.5118 |

来自 SQL 查询

SELECT 
name,
total,
(total/total_sum * 100) AS percentage
FROM
(SELECT
name,
COUNT(*) AS total
FROM
games
WHERE gameStatus = 'win'
AND (
created_at > '2018-03-01 12:02:26'
)
GROUP BY name) AS T
CROSS JOIN (SELECT
COUNT(*) AS total_sum
FROM
games
WHERE gameStatus = 'win'
AND (
created_at > '2018-03-01 12:02:26'
) ) TS;

简而言之,我想从所有获胜的比赛中找出每个玩家获胜的百分比是多少。我希望无需运行两个 SQL 子查询即可执行此操作。

SQL fiddle http://sqlfiddle.com/#!9/bbbaa5/3

最佳答案

正如我在评论中指出的那样,这两个部分都不需要是子查询。

  SELECT name
, COUNT(*) AS total
, 100 * COUNT(*)/s.total_sum AS percentage
FROM games
CROSS JOIN (
SELECT COUNT(*) AS total_sum
FROM games
WHERE gameStatus = 'win'
AND created_at > '2018-03-01 12:02:26'
) AS s
WHERE gameStatus = 'win'
AND created_at > '2018-03-01 12:02:26'
GROUP BY name
;

但不确定这是否真的会更快;如果 MySQL 最终以几乎相同的方式处理它们,我不会感到惊讶。

关于MySQL百分比将计数除以总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332694/

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