Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get highest marks scored by students in each school

Tags:

sql

sql-server

I have table STUDENT_MARKS:

SCHOOL_ID   STUDENT_ID      TTL_MARKS
--------------------------------------
8           24              78
8           25              76
9           33              88
9           34              85
9           35              88
10          41              68
10          42              68
10          43              68

My output should be:

SCHOOL_ID   STUDENT_ID      TTL_MARKS
--------------------------------------
8           24              78
9           33              88
9           35              88
10          41              68
10          42              68
10          43              68

I am trying with this query but not successful ::

SELECT 
    SCHOOL_ID, 
    STUDENT_ID, 
    MAX(TTL_MARKS) OVER(PARTITION BY SCHOOL_ID) 
FROM STUDENT_MARKS

How can I get the desired result in SQL Server? Please help!

like image 879
nischalinn Avatar asked Nov 25 '25 02:11

nischalinn


1 Answers

You seem to want the original rows. So one method uses a subquery with window functions:

select sm.*
from (select sm.*, max(sm.ttl_marks) over (partition by school_id) as max_ttl_marks
      from student_marks sm
     ) sm
where ttl_marks = max_ttl_marks;

This query uses a window function to get the maximum marks for each school. The outer query then filters the rows so only the students with the maximum marks are in the result set.

like image 64
Gordon Linoff Avatar answered Nov 27 '25 15:11

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!