Practice06 Sol
Practice06 Sol
2. Query the information of students who have studied the course with id ‘01’ but have not
studied the course with id ‘02’.
Answer:
SELECT
*
FROM
Student
WHERE
s_id IN (
SELECT
s_id
FROM
Sc
WHERE
c_id = '01'
)
AND s_id NOT IN (
SELECT
s_id
FROM
Sc
WHERE
c_id = '02'
);
3. Query the names of students who have not studied any course taught by teacher ‘ZHANG
San’.
Answer:
SELECT S.s_name
FROM Student S
WHERE
NOT EXISTS (
SELECT c_id
FROM Sc
WHERE Sc.s_id=S.s_id
INTERSECT
SELECT c_id
FROM Course C, Teacher T
WHERE C.t_id = T.t_id AND t_name = 'ZHANG San'
);
4. Query course ids and the number of students enrolling for each course.
Answer:
SELECT
c_id, COUNT(s_id)
FROM
Sc
GROUP BY
c_id;
5. Query the average score of each course, and sort the results in descending order of the
average score.
Answer:
SELECT
c_id, AVG(s_Sc)
FROM
Sc
GROUP BY
c_id
ORDER BY
AVG(s_Sc) DESC;
8. Display student id and average grades for each student in descending order of average
grades.
Answer:
SELECT
Sc.s_id, AVG(s_Sc)
FROM
Sc
GROUP BY
Sc.s_id
ORDER BY
AVG(s_Sc) DESC;
9. Query the information of other students who took at least one same course as the student
with id ‘01’.
Answer:
SELECT
DISTINCT Student.*
FROM
Student, SC
WHERE
Student.s_id=SC.s_id
AND SC.c_id IN (
SELECT
a.c_id
FROM
Sc a
WHERE
a.s_id = '01'
)
AND Student.s_id != '01';
10. Query the information of the students who got highest score in the ‘Math’ course.
Answer:
SELECT
*
FROM
Student
WHERE
Student.s_id IN (
SELECT s_id
FROM Sc
WHERE (Sc.c_id, Sc.s_sc) = (
SELECT Sc.c_id, MAX(Sc.s_sc)
FROM Sc, Course
WHERE Sc.c_id = Course.c_id
AND Course.c_name = 'Math'
Group BY Sc.c_id
)
);