1
students 

Name  |  Subject  | Marks
 --------------------------
 a        M          20
 b        M          25  
 c        M          30
 d        M          30
 d        C          44 
 e        C          45
 f        C          46 
 g        H          40
 h        H          40

Result Should be

Name  |  Subject  | Max(Marks)
 --------------------------
 c        M          30 
 d        M          30
 f        C          46 
 g        H          40
 h        H          40

I have tried

SELECT Name
     , Subject
     , MAX(Marks) 
  FROM students 
 GROUP 
    BY subject.

Name  |  Subject  | MAX(Marks)
--------------------------
c        M          30
f        C          46 
g        H          40

It's showing only first MAX details not other. please help me out on this query.

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Gopal
  • 11
  • 3
  • will it work? `order by Marks desc limit 0, 2` – Girish Apr 09 '21 at 10:22
  • Correct Anser: SELECT students.Name, students.Subject, students.Marks FROM students INNER JOIN ( SELECT s.Subject, MAX(s.Marks) AS Marks FROM students s GROUP BY s.Subject ) AS m ON m.Subject = students.Subject AND students.Marks = m.Marks ORDER BY students.subject ASC – Gopal Apr 09 '21 at 10:55

2 Answers2

2

First you need to find the max marks for the group, then return all rows that have the same mark.

You could do this via a window query, cte, nested select, or a correlated sub query... in this case we'll use a sub query as the syntax should work across many rdbms:

SELECT students.Name, students.Subject, students.Marks
FROM students
INNER JOIN (
    SELECT s.Subject, MAX(s.Marks) AS Marks
    FROM students s
    GROUP BY s.Subject
) AS MaxMarks m ON m.Subject = students.Subject
WHERE students.Marks = m.Marks
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
0

This would typically be approached using window functions, in particular rank() or dense_rank():

SELECT s.*
FROM (SELECT Name, Subject, MAX(Marks) as max_marks,
             RANK() OVER (PARTITION BY Subject ORDER BY MAX(Marks) DESC) as seqnum
      FROM students 
      GROUP BY subject
     ) s
WHERE seqnum = 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786