This is the last problem I have to deal with in my application and I hope someone will help because I'm clueless, I did my research and cannot find a proper solution.
I have an 'University Administration' application. I need to make a report with few tables included.
The problem is in SQL Query i have to finish. Query needs to MAKE LIST OF BEST 'n' STUDENTS, and the condition for student to be 'best' is grade AVERAGE.
I have 3 columns (students.stID & examines.grades). I need to get an average of my 'examines.grades' column, sort the table from highest (average grade) to the lowest, and I need to filter 'n' best 'averages'.
The user would enter the filter number and as I said, the app needs to show 'n' best averages.
Problem is in my SQL knowledge (not mySQL literaly but T-SQL). This is what I've donne with my SQL query, but the problem lies in the "SELECT TOP" because when I press my button, the app takes average only from TOP 'n' rows selected.
SELECT TOP(@topParam) student.ID, AVG(examines.grades)
FROM examines INNER JOIN
student ON examines.stID = student.stID
WHERE (examines.grades > 1)
For example:
StudentID Grade
1 2
2 5
1 5
2 2
2 4
2 2
EXIT:
StudentID Grade_Average
1 3.5
2 3.25
Being impatient, I think this is what you are looking for. You didn't specify which SQL Server version you're using although.
If you'll provide some basic data, I'll adapt query for your needs.
Result:
Quick explain:
Query finds grades average in derived table and later queries it sorting by it. Another tip: You could use
WITH TIES
option inTOP
clause to get more students if there would be multiple students who could fit for 3rd position.If you'd like to make procedure as I suggested in comments, use this snippet:
And later call it like that. It's a good way to encapsulate your logic.