小编典典

按不在选择中的字段分组

sql

我想查找一位讲师在特定年份教过多少个模块,并想要选择该讲师的姓名和该讲师的模块数。

问题在于,因为我正在选择Name,并且必须按名称对其进行分组才能使其正常工作。但是,如果有两个讲师姓名相同,该怎么办?然后,sql将使它们合而为一,这将是错误的输出。

因此,我真正想做的是选择,name但选择group by id,而sql不允许我这样做。有办法解决吗?

下表是:

Lecturer(lecturerID, lecturerName)
Teaches(lecturerID, moduleID, year)

到目前为止,这是我的查询:

SELECT l.lecturerName, COUNT(moduleID) AS NumOfModules
FROM Lecturer l , Teaches t
WHERE l.lecturerID = t.lecturerID
AND year = 2011
GROUP BY l.lecturerName --I want lectureID here, but it doesn't run if I do that

阅读 191

收藏
2021-03-23

共1个答案

小编典典

SELECT a.lecturerName, b.NumOfModules
FROM Lecturer a,(
SELECT l.lecturerID, COUNT(moduleID) AS NumOfModules
    FROM Lecturer l , Teaches t
    WHERE l.lecturerID = t.lecturerID
    AND year = 2011
    GROUP BY l.lecturerID) b
WHERE a.lecturerID = b.lecturerID
2021-03-23