gpt4 book ai didi

sql [db2] 带条件的选择语句

转载 作者:行者123 更新时间:2023-12-02 22:12:46 27 4
gpt4 key购买 nike

我有两个表。
player1 有行 username, score, game_id, ...
player2 有行用户名、得分、游戏 ID...
你如何为同一个game_id选择得分最高的用户名?

我有的是

SELECT player1.username winning,
player1.points,
player1.game_id
FROM player1
INNER JOIN player2 ON player1.game_id = player2.game_id
WHERE player1.points > player2.points

SELECT player2.username winning,
player2.points,
player2.game_id
FROM player1
INNER JOIN player2 ON player1.game_id = player2.game_id
WHERE player2.points > player1.points

最佳答案

应该这样做:

SELECT
game_id,
CASE WHEN p1.score > p2.score THEN p1.username ELSE p2.username END AS winner
FROM
player1 p1
INNER JOIN
player2 p2 ON p1.game_id = p2.game_id
ORDER BY
p1.game_id ASC

正如Darius提到的,你可能希望根据平局的情况调整CASE语句,你可以将它改成这样:

CASE WHEN p1.score > p2.score THEN p1.username WHEN p1.score < p2.score THEN p2.username ELSE 'Draw' END AS winner

这实际上取决于您想要在该场景中显示的内容。

关于sql [db2] 带条件的选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970631/

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