I have the following table
Name | Subject | Marks
--------------------------
a M 20
b M 25
c M 30
d C 44
e C 45
f C 46
g H 20
Here I have a "Student" table I want to get the Name of the student who got
Max marks from each subject from the student table like the following OUTPUT.
Name | Subject | Marks
c M 30
f c 46
g h 20
9条答案
按热度按时间wtlkbnrh1#
You can use the ROW_NUMBER function to return only the "best" row per subject:
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
Results:
uurity8g2#
You can use other functions and cte also to get the result..
eg : 1
Eg : 2 : use of cte and dense_rank function
rryofs0p3#
This Basic Query should work for your req.
Tried in SQLFiddle
Note: Used SQLite for check
dfuffjeb4#
thtygnil5#
SELECT
Max(Name) as Name, Subject, Max(Marks) as MarksFROM
Studentgroup by
Subjectars1skjm6#
A Similar problem :
Write a query to display the name(s) of the students who have secured the maximum marks in each subject, ordered by subject name in ascending order.
If there are multiple toppers, display their names in alphabetical order.
Display it as subject_name and student_name.
O/P:
Solution for this problem:
tgabmvqs7#
The below query will work perfectly:
qoefvg9y8#
This query will work
6tqwzwtp9#
By using GROUP BY and Having clause that give you simple sql query to find maximum marks in each subject