SQL嵌套聚合函数

时间:2018-10-03 15:49:46

标签: sql postgresql

我有桌子:

Student(sID, firstName, lastName, email, cgpa)
Course(cNum, name, dept, credit)
Offering(oID, cNum, dept, year, term, instructor)
Took(sID, oID, grade)

我正在尝试完成问题:

Find all courses for the term 2017F and the current enrolment

我目前有这个查询来获取每个课程的注册学生人数:

SELECT Took.oID, COUNT(*) AS enrolment
FROM Took
GROUP BY Took.oID
HAVING COUNT(*) > 0

嵌套在此语句中,以获取我希望其注册人数正确的课程:

SELECT oID
FROM Offering
WHERE Offering.year = 2017
AND Offering.term = 'F'

这两个查询都嵌套在其中以将所有内容绑定在一起:

SELECT DISTINCT Offering.cNum, Course.name, (I WOULD LIKE COUNT(*) AS enrolment HERE)
FROM Offering NATURAL JOIN Course
WHERE Offering.oID IN (
            SELECT oID
            FROM Offering
            WHERE Offering.year = 2017
            AND Offering.term = 'F'
            AND oID IN (
                    SELECT Took.oID, COUNT(*) AS enrolment
                    FROM Took
                    GROUP BY Took.oID
                    HAVING COUNT(*) > 0))
GROUP BY Offering.cNum, Course.name;

我的问题是,如何将结果COUNT(*)AS注册从最远的嵌套查询传递到初始查询,以便它可以显示在结果投影中? (这是家庭作业)

3 个答案:

答案 0 :(得分:1)

如果我正确理解,您可以尝试在fromJOIN中使用子查询,而不是where子查询。

然后您可以从子查询中获取count列。

SELECT DISTINCT Offering.cNum, Course.name,t1.enrolment
FROM Offering 
JOIN (
    SELECT Took.oID, 
        COUNT(*) AS enrolment
    FROM Took
    GROUP BY Took.oID
    HAVING COUNT(*) > 0
) t1 on t1.oID = Offering.oID
NATURAL JOIN Course
WHERE Offering.year = 2017 AND Offering.term = 'F'

答案 1 :(得分:1)

尝试一下

SELECT c.*
    , (
        SELECT COUNT(*)
        FROM Took
        WHERE oID = o.oID
    ) AS theCount
FROM Course c
JOIN Offering o ON o.cNum = c.cNum
WHERE o.year = 2017 AND o.term = 'F'

答案 2 :(得分:0)

可能是这个

SELECT Course.name, Course.cNum, count(*) as enrolment
FROM Course
JOIN Offering ON Course.cNum = Offering.cNum
JOIN Took ON Offering.oID = Took.oID
WHERE Offering.year = 2017
AND Offering.term = 'F'
GROUP BY Course.name, Course.cNum
HAVING count(*) > 0;