简体   繁体   中英

Need help writing SQL queries(joins, subqueries)

Given the following schema, I'm supposed to write queries for the questions.

My first query runs but I get no result and the second one gives the subquery returns more than one row error.

student (sid, sname, sex, birthdate, gpa)
prof (pname, dname)
course (cnum, dname, cname)
section (cnum, secnum, pname)
enroll (sid, cnum, secnum, grade)
  1. For each course, return the number of sections (numsections), total number of students enrolled (numstudents), average grade (avggrade), and number of distinct professors who taught the course (numprofs). Only show courses in Chemistry or Computer Science department. Make sure to show courses even if they have no students. Do not show a course if there are no professors teaching that course.

  2. Return the students who received a higher grade than their course section average in at least two courses. Order by number of courses higher than the average and only show top 5.

Sql query:

SELECT C.cnum, C.cname, COUNT(*) AS numsections, COUNT(E.sid) AS numstudents, 
AVG(E.grade) AS avggrade, COUNT(P.pname) AS numprofs
FROM course C 
    JOIN section S ON C.cnum = S.cnum
    JOIN enroll E ON C.cnum = E.cnum
    JOIN prof P ON S.pname = P.pname
WHERE C.cname = 'Chemistry' OR C.cname = 'Computer Science'
GROUP BY C.cnum, C.cname;`


SELECT S.sid, S.sname
FROM student S 
     LEFT JOIN enroll E ON S.sid = E.sid
WHERE E.grade > (SELECT AVG(grade)
                FROM course C JOIN enroll E2
                ON C.cnum = E2.cnum
                GROUP BY C.cnum
                LIMIT 5);`

About the second query...

Your subquery is getting more than 1 row of data. To use "<" you need yo be sure you are bringing only 1 row and only 1 column.

And if I understand correctly, you only have to show the top 5 students order by the number of times the are better than the average of the course.. I realice this is a learning example so it wont help if I give you the query..

You need to select the top 5 students, but to know that you have to COUNT() the number of times that their GRADE was greater than the AVG() of each course they have taken, at some point in your subquery you sould have the list of students order by the number of times they achive beeing above the average.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM