写两个查询(根据平均成绩对学生和城市进行排序)

时间:2014-08-10 11:28:07

标签: sql

我有三张桌子:

1) Students: studentID (KEY), name, surname, address
2) Exams: examID (KEY), examName
3) Grades: studenID (KEY), examID(KEY), grade

如何编写SQL查询以显示最佳学生(例如平均成绩高于9的学生)?

如何根据学生的平均成绩编写SQL查询来对城市(列地址)进行排名?

我是系统工程师,使用Unix和Linux系统,我是SQL的新手,我只了解SQL基础知识,过去三天我试图这样做,没有成功,所以请帮忙我。我认为对于那些在SQL方面经验丰富的人来说,这不是一件复杂的事情。非常感谢。

2 个答案:

答案 0 :(得分:0)

第一个向最佳学生展示的问题:

  SELECT student.surname, students.surename, students.address
  FROM 
  students INNER JOIN Grades ON Grades.StudentID=Students.StudentID 
  INNER JOIN Exams ON Grades.examID=exams.examID WHERE Grades.grade=
  (SELECT MAX(grade) FROM Grades WHERE examID=exams.examID) 

您对城市进行排名的第二个问题:

  SELECT students.address
  FROM 
  students INNER JOIN Grades ON Grades.StudentID=Students.StudentID 
  INNER JOIN Exams ON Grades.examID=exams.examID order by grades.grade DESC

答案 1 :(得分:0)

请参阅此处的小提琴:

LINK 1 http://sqlfiddle.com/#!4/ab4de6/19

LINK 2 http://sqlfiddle.com/#!4/ab4de6/32

以下查询应该可以帮助您:

--List of Students having Average grade >=9

SELECT S.studentID, S.NAME, S.SURNAME, S.ADDRESS, A.AVG_GRADE FROM 
STUDENTS S JOIN
( 
   SELECT studentID, AVG(GRADE) AVG_GRADE FROM GRADES
   GROUP BY studentID

)  A
ON S.studentID = A.studentID
AND A.AVG_GRADE >=9

ORDER BY A.AVG_GRADE, S.studentID;


--------------------------------------------------------------------

--- Rank cities
SELECT A.ADDRESS, A.AVG_GRADE, ROWNUM RANKING FROM
(
    SELECT S.ADDRESS, AVG(G.GRADE) AVG_GRADE FROM
    STUDENTS  S JOIN GRADES  G
    ON S.STUDENTID = G.STUDENTID
    GROUP BY S.ADDRESS
    ORDER BY 2 DESC
  ) A;

您需要了解以下概念。

  1. INNER QUERY / SUB QUERY
  2. JOINS
  3. AGGREGATE FUNCTIONS(平均值计算)
  4. GROUP BY
  5. ORDER BY
  6. ROWNUM