SQL查找教师课程查询

时间:2018-02-02 20:11:43

标签: sql oracle oracle-sqldeveloper

我正在努力让老师FIRSTNAMELASTNAME和他获得的课程数量。 Oracle数据库。 CLASS表包含以下列:CLASSIDTEACHERIDCLASSNAME当前代码:

SELECT DISTINCT FIRSTNAME, LASTNAME, COUNT(TEACHERID)
FROM PERSON 
INNER JOIN TEACHER T ON PERSON.PERSONID = T.TEACHERID 
INNER JOIN CLASS C ON T.TEACHERID = C.TEACHERID
WHERE T.TEACHERID = C.TEACHERID;

我的错误在哪里?

3 个答案:

答案 0 :(得分:1)

听起来你需要一个GroupBy:

SELECT FIRSTNAME, LASTNAME, COUNT(T.TEACHERID)
FROM PERSON 
INNER JOIN TEACHER T ON PERSON.PERSONID = T.TEACHERID 
INNER JOIN CLASS C ON T.TEACHERID = C.TEACHERID
GROUP BY LASTNAME,FIRSTNAME

顺便说一下,我最初删除了这个答案,因为这不是一个好的分组方法。我更喜欢按TEACHERID进行分组,然后加入以获取名称,而不是按名称分组。

我认为这是一种更好的方法:

SELECT FIRSTNAME, LASTNAME, C.NUMCLASSES
FROM PERSON 
INNER JOIN TEACHER T ON PERSON.PERSONID = T.TEACHERID 
INNER JOIN (SELECT TEACHERID, COUNT(CLASSID) AS NUMCLASSES FROM CLASS GROUP BY TEACHERID) C
ON C.TEACHERID=T.TEACHERID

答案 1 :(得分:0)

您在WHERE子句

之后缺少GROUP BY子句
  

GROUP BY FIRSTNAME,LASTNAME - 除了COUNT

等聚合函数中的所有列之外的所有列

答案 2 :(得分:0)

可能你可以试试

SELECT FIRSTNAME, LASTNAME, 
(select COUNT(C.TEACHERID) form CLASS C ON T.TEACHERID = C.TEACHERID)
as COURSECOUNT
FROM PERSON 
INNER JOIN TEACHER T ON PERSON.PERSONID = T.TEACHERID