gpt4 book ai didi

从一个表中的特定组中选择 MIN 的 SQL 更新

转载 作者:行者123 更新时间:2023-12-01 14:00:00 25 4
gpt4 key购买 nike

我真的是 SQL 的新手。我搜索了一个符合我要求的答案,我会理解已经完成的工作——我失败了。所以这里是:我正在制作一个程序来保存马拉松比赛的数据。所以我有一个表 StageResults 包含列: StageNo ParticipantNumber ParticipantGroup Time(如在完整秒的距离时间因此 int) 和 Points一个例子看起来像:

 - 1|01|M21|500|X
- 1|22|M21|550|X
- 1|45|M21|530|X
- 1|47|F09|600|X
- 1|09|F09|630|X
- 2|01|M21|515|X
- 2|45|M21|520|X

所以我希望每个阶段中每个组中最快的成员获得 1000 分。在我的脑海深处,我觉得我可以为此编写一个查询,我尝试了几个小时。我现在拥有的最好的是:

SELECT c1.ParticipantNumber, c1.ParticipantGroup, c1.Time
FROM StageResults AS c1
LEFT JOIN StageResults AS c2
ON c1.StageNo = c2.StageNo
AND c1.ParticipantGroup = c2.ParticipantGroup
AND c1.Time < c2.Time;

我在 INSERT 语句下使用了它。没有语法错误但错误,我正在尝试插入重复的主键。我认为这可以通过添加 GROUP BY 语句来解决。所以我还没有真正测试过这个。

我最终想为每个运行(阶段)和每个组中最快的参与者设置 1000 分(我的意思是它应该自动发生)。然后根据最快的人,计算所有其他人的分数。(但那是以后的事,如果我弄清楚如何添加这些 1k 点,我认为管理不善)所以我必须在 UPDATE 语句中添加这个逻辑。我做不到。我只是迷路了。

欢迎任何建议。也许我完全在错误的方向思考如何做到这一点。任何帮助将不胜感激。

最佳答案

标识行的查询可能如下所示:

select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
);

接下来的问题是如何将其转化为更新。对于 MySQL,你会这样做:

update table StageResults sr join
(select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
)
) toupdate
on toupdate.ParticpantNumber = sr.ParticpantNumber
set sr.points = sr.points + 1000;

SQL Server 的语法会有点不同,但您的问题已标记为 MySQL。

编辑:

对于 SQL 服务器:

with toupdate as (select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
)
)
update toupdate
set points = points + 1000;

关于从一个表中的特定组中选择 MIN 的 SQL 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743177/

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