获取最大3列之和的行-mysql

afdcj2ne  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(393)

我被一些查询逻辑困住了。我有一张table叫 student . 表中有学生每学期的分数。有 n 学期数。我需要得到每个学期最高分(mark1+mark2+mark3)学生的姓名和id。
这是我的table结构

|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  |

需要的输出

|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   |

我想得到马克斯

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

iqxoj9l91#

您必须按sem分组,以获得子查询中每个sem的最大标记,一旦获得每个sem的最大标记,就可以在这样的子查询中使用in,

SELECT *, mark1+mark2+mark3 AS maxmark 
from student
where (sem, mark1 + mark2 + mark3) in (
SELECT sem, MAX(mark1 + mark2 + mark3) AS maxmark
FROM student
GROUP BY sem )

输出

|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   |

你可以从网上了解更多关于,https://www.techonthenet.com/mysql/in.php 祝你好运,希望这有帮助。

mrzz3bfm

mrzz3bfm2#

此查询将提供所需的结果。它将student表连接到一个每个学期都有最高分数的表中,只显示该学期达到最高分数的学生(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演示

相关问题