分组依据中的Count(*)-返回1,而不是“ 0”

时间:2018-07-17 07:28:20

标签: oracle group-by count

我正在使用下面的oracle查询来获取行数。

SELECT T.ID,T.NAME,COUNT(*) AS NO_OF_STUDENTS FROM STUDENT S RIGHT JOIN 
TEACHER T ON S.TEACHER_ID = T.ID
GROUP BY T.ID,T.NAME ORDER BY T.ID 

实际结果应为:

TEACHER 1 - 10 STUDENTS   
TEACHER 2 - 5 STUDENTS   
TEACHER 3 - 0 STUDENT

我得到的结果是:

TEACHER 1 - 10 STUDENTS   
TEACHER 2 - 5 STUDENTS   
TEACHER 3 - 1 STUDENT   

由于教师3没有任何学生,因此结果应为0学生。但是我得到的结果是1个学生。

1 个答案:

答案 0 :(得分:0)

您需要计算与外部连接的表中的特定列(不使用*,包括空值),因为该列可能没有匹配的数据。所以:

SELECT T.ID, T.NAME, COUNT(S.ID) AS NO_OF_STUDENTS
FROM STUDENT S
RIGHT JOIN TEACHER T ON S.TEACHER_ID = T.ID
GROUP BY T.ID, T.NAME
ORDER BY T.ID

唯一的区别是COUNT(S.ID)而不是COUNT(*)

具有通过CTE提供的虚构数据的简单演示:

with teacher (id, name) as (
  select 1, 'Teacher 1' from dual
  union all select 2, 'Teacher 2' from dual
  union all select 3, 'Teacher 3' from dual
),
student (id, teacher_id) as (
  select level, 1 from dual connect by level <= 10
  union all
  select level + 10, 2 from dual connect by level <= 5
)  
SELECT T.ID, T.NAME, COUNT(S.ID) AS NO_OF_STUDENTS
FROM STUDENT S
RIGHT JOIN TEACHER T ON S.TEACHER_ID = T.ID
GROUP BY T.ID, T.NAME
ORDER BY T.ID;

        ID NAME      NO_OF_STUDENTS
---------- --------- --------------
         1 Teacher 1             10
         2 Teacher 2              5
         3 Teacher 3              0

您也可以将其作为左联接来执行,我觉得这更直观:

SELECT T.ID, T.NAME, COUNT(S.ID) AS NO_OF_STUDENTS
FROM TEACHER T
LEFT JOIN STUDENT S ON S.TEACHER_ID = T.ID
GROUP BY T.ID, T.NAME
ORDER BY T.ID 

获得相同的结果。