0

I have 2 tables: teacher, & class. here's the descriptions:

TEACHER
 ----------------
 TEACHER_ID
 FIRST_NAME
 LAST_NAME
 TYPE_CODE
 HOME_ROOM_NUM
 PHONE_NUM
 START_DATE
 HOME_STATE
 SCHOOL_ID

 Class
 --------------------
 CLASS_ID
 CLASS_NAME
 TEACHER_ID
 MAX_SEATS_AVAILABLE

Im trying to figure out how to count the number of classes a given teacher teaches. here's what I have tried: 1. How many classes does Lisa Jones teach, if any?

SQL> select teacher.last_name, teacher.first_name, class.class_name as 
  2  from teacher, class
  3  where teacher.teacher_id = '2'
  4  AND class.teacher_id = '2';

here's the result I get:

LAST_NAME         FIRST_NAME        CLASS_ID CLASS_NAME           TEACHER_ID  MAX_SEATS_AVAILABLE

----------------- ----------------- -------- -------------------- ----------- --------------------
JONES             LISA               2       Basic CALCULUS       2           10
JONES             LISA               9       Physics 230          2           20

I just need teacher name, Id, and # of classes, not having any luck w/ the COUNT function.

4

2 回答 2

4

我建议消除已弃用的隐式连接并替换为标准的显式连接:只需要 aGROUP BY即可COUNT()正常工作。

SELECT t.last_name, t.first_name, t.Teacher_ID, COUNT(DISTINCT CLASS_ID) as Classes_Count 
FROM teacher t
JOIN class c
  ON t.Teacher_ID = c.Teacher_ID
WHERE t.Teacher_ID = '2'
GROUP BY t.last_name, t.first_name, t.Teacher_ID

您可能需要也可能不需要DISTINCT计数,具体取决于数据的性质。

于 2013-09-23T02:58:25.163 回答
0

我认为@GOAT CO 解决方案是正确的。这个 squery 在没有 JOIN 语句的情况下工作:

select t.last_name, t.first_name, c.class_name, COUNT(DISTINCT c.CLASS_ID) as Classes_Count from teacher t, class c where t.teacher_id = c.teacher_id and t.teacher_id = 1 GROUP BY t.LAST_NAME, t.FIRST_NAME, t.TEACHER_ID;

编辑:现在我为教师和班级表添加别名并将组语句添加到脚本中。你能试试吗?我只在 Fiddle 上测试过。

这是SQL FIDDLE 链接。

EDIT2: 同时我检查ORA-00937: not a single-group group function并找到了这个和这个主题。但是这个脚本没有得到这个异常。如果您修改了声明,请分享!

于 2013-09-23T08:00:34.083 回答