我是Microsoft Access的新手。如果我的问题看似微不足道,请接受我的道歉。
我正在尝试在Access中编写一个查询,该查询显示每月注册课程的学生总数。我有两个名为course
和confirmed_enrollments
的表。
course
表只有一个名为course_name
的字段,而confirmed_enrolments
表有三个字段; student_code
,course_name
和month_of_enrol
。
我想在我的查询中显示所有 course_name
(无论是否注册了学生)以及他们在特定月份的总注册量。我写的查询只显示了已注册的课程,并没有考虑没有注册的课程。
寻求你的帮助。这是我的SQL代码:
SELECT Course.Course_name,
Count(confirmed_enrolments.Student_code) AS CountOfStudent_code,
confirmed_enrolments.Month_of_enrol
FROM Course
LEFT JOIN confirmed_enrolments
ON Course.Course_name = confirmed_enrolments.Course_name
GROUP BY Course.Course_name, confirmed_enrolments.Month_of_enrol
HAVING confirmed_enrolments.Month_of_enrol="December 2016";
答案 0 :(得分:1)
我想你打算这样:
SELECT c.Course_name, Count(ce.Student_code) AS CountOfStudent_code,
ce.Month_of_enrol
FROM Course as c LEFT JOIN
(SELECT ce.*
FROM confirmed_enrolments as ce
WHERE ce.Month_of_enrol = "December 2016"
) as ce
ON c.Course_name = ce.Course_name
GROUP BY c.Course_name, ce.Month_of_enrol;
在查询中使用HAVING
子句很聪明,但是您在第二个表中进行过滤 - 值为NULL
而不是指定的月份 - 当没有匹配时
问题是该条件位于 second 表中。在普通的SQL方言中,您可以写:
SELECT c.Course_name, Count(ce.Student_code) AS CountOfStudent_code,
ce.Month_of_enrol
FROM Course as c LEFT JOIN
confirmed_enrolments as ce
ON c.Course_name = ce.Course_name AND
ce.Month_of_enrol = "December 2016"
GROUP BY c.Course_name, ce.Month_of_enrol;
但MS Access似乎不允许在LEFT JOIN
进行第二次比较。
顺便说一下,编写查询的另一种方法是使用相关的子查询:
SELECT c.Course_name,
(SELECDT Count(ce.*)
FROM confirmed_enrolments as ce
WHERE ce.Month_of_enrol = "December 2016"
) AS CountOfStudent_code,
"December 2016" as ce.Month_of_enrol
FROM Course as c ;