gpt4 book ai didi

mysql - 获取最大总和为 3 列的行 - Mysql

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

我被一些查询逻辑困住了。我有一个名为 student 的表。表中有每个学期学生的成绩。有 n 个学期。我需要获取每个学期最高分(mark1+mark2+mark3)的学生的姓名和ID。

This is my table structure

|id| name | mark1| mark2| mark3| sem|
|1 | Harry| 8 | 9 | 9 | 1 |
|2 | John | 10 | 8 | 10 | 1 |
|3 | Derek| 4 | 5 | 8 | 1 |
|4 | Dona | 8 | 9 | 5 | 1 |
|5 | Ammy | 9 | 9 | 9 | 2 |
|6 | Kate | 10 | 7 | 10 | 2 |
|7 | Aby | 3 | 5 | 4 | 2 |
|8 | Eliza| 5 | 9 | 5 | 2 |

Needed output

|id| name | mark1| mark2| mark3| sem| maxmark|
|2 | John | 10 | 8 | 10 | 1 | 28 |
|5 | Ammy | 9 | 9 | 9 | 2 | 27 |
|6 | Kate | 10 | 7 | 10 | 2 | 27 |

MY ATTEMPT TO GET maxmark

SELECT *, (MAX(`mark1` + `mark2` + `mark3`)) AS maxmark
FROM `stud`
GROUP BY `studid`

最佳答案

此查询将为您提供您想要的结果。它将学生表与包含每个学期最高分的表连接起来,仅显示获得该学期最高分的学生 (s2.maxmark = s1.mark1+s1.mark2+s1.mark3)。

SELECT s1.*, s2.maxmark
FROM student s1
JOIN (SELECT sem, MAX(mark1 + mark2 + mark3) AS maxmark
FROM student
GROUP BY sem) s2
ON s2.sem = s1.sem AND s2.maxmark = s1.mark1+s1.mark2+s1.mark3

输出:

id  name    mark1   mark2   mark3   sem     maxmark
2 John 10 8 10 1 28
5 Ammy 9 9 9 2 27
6 Kate 10 7 10 2 27

SQLFiddle Demo

关于mysql - 获取最大总和为 3 列的行 - Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341973/

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