Possible Duplicate:
sql to select top 10 records
Assuming you have one table with StuId, StuName, Subject, Grade. You are required to provide a subquery to return a list of honor students (top 10 percent), sorted by their grade point average.
for example, if I have 10 student whose average grade is 100,90,80,…10.
It is required to output the first student name whose average is 100. Only one student grade is output. So I can’t use limit 10
I am using mysql 5.1.
Here is my query:
SELECT Stuname, TOP 10 Avg(Grade) as GPA
FROM Table
GROUP BY Stuid
ORDER BY GPA
The query is not correct because of the TOP 10. Checking MYSQL 5.1 reference, it does not support top 10.
According to comments, I dont think it can be resolved using one query, so I come up with a method:
F(conn){
Statement stmt;
int top10percnet = 0;
try{
stmt = conn.createStatement;
String query = "select CEIL(count(stuname)*10/100) as 10percent from grades";
ResultSet rs = stmt.execute(query);
while(rs.next()){
top10percent = rs.getString("10percent");
}
query = "select stuname, avg(grade) as average from grades group by stuname order
by average desc limit " + Integer.toString(top10percnet);
rs=stmt.execute(query);
while(rs.next()){
...// output result
}
}
catch(SQLException e){
}
}
First query will return the 10% of the students.CEIL is used to convert it into integer.
Second query is to retrieve the data.
The count calculated from the first query is set as the limit to the second query.