从3个不同的主题中找到一个ID的最大值(标记),类似地为第二个ID等等。
表名-学生
+---------+---------+-------+
| stud_id | Subj | Marks |
+---------+---------+-------+
| 1 | ENGLISH | 60 |
+---------+---------+-------+
| 1 | MATHS | 50 |
+---------+---------+-------+
| 1 | HINDI | 65 |
+---------+---------+-------+
| 2 | ENGLISH | 70 |
+---------+---------+-------+
| 2 | MATHS | 20 |
+---------+---------+-------+
| 2 | HINDI | 57 |
+---------+---------+-------+
| 3 | ENGLISH | 72 |
+---------+---------+-------+
| 3 | MATHS | 88 |
+---------+---------+-------+
| 3 | HINDI | 62 |
+---------+---------+-------+
结果应为:
+---------+---------+-------+
| stud_id | Subj | Marks |
+---------+---------+-------+
| 1 | HINDI | 65 |
+---------+---------+-------+
| 2 | ENGLISH | 70 |
+---------+---------+-------+
| 3 | MATHS | 88 |
+---------+---------+-------+
查询:
SELECT STUD_ID, SUBJ, MAX(MARKS) marks FROM STUDENT group by id;
答案 0 :(得分:0)
在相等的情况下,我同时拥有两个ID。
如果不是这种情况,请删除GROUP BY
并将GROUP_CONCAT()
替换为DISTINCT s1.Subj
SELECT GROUP_CONCAT(DISTINCT s1.stud_id
ORDER BY s1.stud_id ASC SEPARATOR ', '),
s1.Subj,
s1.Marks
FROM Student s1
LEFT JOIN Student s2 ON s1.Marks < s2.Marks
AND s1.Subj = s2.Subj
WHERE s2.stud_id IS NULL
GROUP BY s1.Subj
您可以测试Here
对于LEFT JOIN
,实际具有最大值的行将在右侧具有NULL
。然后,我过滤联接的结果,仅显示右侧为NULL的行。