Frage

Given the schema:

CREATE TABLE Student (
    studentID INT PRIMARY KEY NOT NULL,
    studentName TEXT NOT NULL,
    major TEXT,
    class TEXT CHECK (class IN ("Freshman", "Sophomore", "Junior", "Senior")),
    gpa FLOAT CHECK (gpa IS NULL OR (gpa >= 0 AND gpa <= 4)),
    FOREIGN KEY (major) REFERENCES Dept(deptID) ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE TABLE Dept (
    deptID TEXT PRIMARY KEY NOT NULL CHECK (LENGTH(deptID) <= 4),
    NAME TEXT NOT NULL UNIQUE,
    building TEXT
);

CREATE TABLE Course (
    courseNum INT NOT NULL,
    deptID TEXT NOT NULL,
    courseName TEXT NOT NULL,
    location TEXT,
    meetDay TEXT NOT NULL CHECK (meetDay IN ("MW", "TR", "F")),
    meetTime INT NOT NULL CHECK (meetTime >= '07:00' AND meetTime <= '17:00'),
    PRIMARY KEY (courseNum, deptID),
    FOREIGN KEY (deptID) REFERENCES Dept(deptID) ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE TABLE Enroll (
    courseNum INT NOT NULL,
    deptID TEXT NOT NULL,
    studentID INT NOT NULL,
    PRIMARY KEY (courseNum, deptID, studentID),
    FOREIGN KEY (courseNum, deptID) REFERENCES Course ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (studentID) REFERENCES Student(studentID) ON UPDATE CASCADE ON DELETE CASCADE
);

I'm attempting to find the names, IDs, and the number of courses they are taking, for the students who are taking the highest number of courses. The sELECT to retrieve the names and IDs is simple enough, however I'm having trouble figuring out how to select the number of courses each student is taking, and then find the max of that and use it as a WHERE clause.

This is what I have so far:

SELECT Student.studentName, Student.studentID, COUNT(*) AS count
FROM Enroll
INNER JOIN Student ON Enroll.studentID=Student.studentID
GROUP BY Enroll.studentID
War es hilfreich?

Lösung

So first you get count of all the enrolled classes per student

SELECT COUNT() AS num 
FROM Enroll 
GROUP BY studentID

You can then check that against your existing query using HAVING to get your final query.

SELECT Student.studentName,Student.studentID,COUNT(*) AS count
       FROM Enroll
       INNER JOIN Student ON Enroll.studentID=Student.studentID
       GROUP BY Enroll.studentID
       HAVING COUNT()=(SELECT COUNT() AS num FROM Enroll GROUP BY studentID);

So to recap this basically gets the number which represents the highest number of enrollments for any student, then gets all students where that number is their count of enrollments, thus all students which have the highest, or equal highest number of enrollments.

We use HAVING because it is applied after the GROUP BY, meaning you can't use aggregate functions such as COUNT() in a WHERE clause.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top