2012-09-16 22 views
5

esquema:¿Cómo hacer esta consulta SQL?

Student(studentid,name,age) 
Course(coursename,dept) 
enroll(studentid,coursename,grade) 

tengo que escribir SQL para conocer los nombres de los estudiantes para cada grupo de edad con el grado máximo para los cursos tomados de la historia y la ciencia política departamento.

Mi intento ha sido hasta ahora

SELECT 
    name 
FROM 
    student 
GROUP BY age 
HAVING sid IN 
      (
       SELECT 
        max(grade) 
       FROM 
        enroll e,enroll e1 
       WHERE 
        e.studentid = e1.studentid 
       AND e.coursename = (
            SELECT coursename FROM course 
            WHERE 
             dname like '%History%' 
           ) 
       AND e1.coursename = (
            SELECT coursename FROM course 
            WHERE 
             dname like '%PoliticalScience%' 
            ) 
      ) 
+0

¿Cómo se define el grupo de edad? – vikiiii

+0

Mi conjetura es que el grupo de edad apunta a estudiantes de la misma edad bajo un grupo, por lo tanto, el grupo por edad. – user1675198

Respuesta

0

Usted puede intentar algo en este sentido

select 
    s.name 
from 
    student s, enroll e, 
    (
     select 
      s.age as age, e.coursename as coursename, max(e.grade) as grade 
     from 
      student s, course c, enroll e 
     where 
      s.studentid = e.studentid 
     and c.coursename = e.coursename 
     and (c.dept = 'history' or c.dept = 'political science') 
     group by s.age, e.coursename 
    ) t 
where 
    s.studentid = e.studentid 
and s.age = t.age 
and e.grade = t.grade 
and e.coursename = t.coursename 
2

Usted puede obtener el grado superior utilizando subquery. Intente,

SELECT d.*, 
     f.dept, 
     e.grade 
FROM student d 
     INNER JOIN enroll e 
      on d.studentID = e.studentID 
     INNER JOIN course f 
      ON e.courseName = f.courseName 
     INNER JOIN 
      (
       SELECT a.age, c.dept, Max(b.grade) maxGrade 
       FROM student a 
         INNER JOIN enroll b 
          on a.studentID = b.studentID 
         INNER JOIN course c 
          ON b.courseName = c.courseName 
       WHERE c.dept IN ('history','political science') 
       GROUP BY a.age, c.dept 
      ) topScore 
      ON topscore.age = d.age AND 
       topscore.dept = f.dept AND 
       topscore.maxGrade = e.grade 
Cuestiones relacionadas