gpt4 book ai didi

sql - 如何获得次优值

转载 作者:行者123 更新时间:2023-12-04 13:50:37 24 4
gpt4 key购买 nike

假设我们有两个表:

Players(player_id int)
GameScores(player_id int, session_id int, score int)

我们如何查询每个玩家的第二高分 session ?

例如如果

Players
1
2

GameScores
(player_id, session_id, score)
1 1 10
1 2 20
1 3 40
2 4 10
2 5 20

Then result would be
(player_id, session_id)
1, 2
2, 4

最佳答案

你能试试这个吗

     SELECT GameScores.player_id, GameScores.session_id 
FROM (
SELECT player_id,MAX(score) as SecondScore
FROM GameScores g
WHERE score < (SELECT Max(Score) FROM gameScore where gameScore.player_id = g.player_id)
GROUP BY player_id
) x
INNER JOIN GameScores ON x.player_id = gamescore.player_id
AND x.SecondScore = gamescore.score

这是为每个玩家选择第二高分的查询

SELECT player_id,MAX(score) as SecondScore
FROM GameScores g
WHERE score < (SELECT Max(Score) FROM gameScore where gameScore.player_id = g.player_id)
GROUP BY player_id

您不能在此查询中按 session 分组。所以这就是为什么您需要将其放入子查询并将其加入 gamescore 以获取 session_id

关于sql - 如何获得次优值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13494261/

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