日期:2014-05-17  浏览次数:20393 次

这个统计的查询语句怎么写?
用到两个表,teacher和student。

teacher的字段和值如下:
id name status
1 王老师 0
2 李老师 1
3 余老师 1
4 张老师 2


student的字段和值如下:
id name teacherId
1 张三 1
2 李四 1
3 王五 2
4 宋六 1
5 郑七 2

我想查出每个老师在表student中出现的次数,比如这个例子的结果显示为:
name times
王老师 3
李老师 2
余老师 0
张老师 0
这个SQL语句怎么写?

------解决方案--------------------
SQL code

select name,count(student.id) times
from teacher
left join student on teacher.id=student.teacherId;
group by teacher.name--少了

------解决方案--------------------
SQL code
;with cte_temp as (
    select teacherId,COUNT(1) as times
)
select a.name,b.times
from teacher a 
left join cte_temp b
on a.id = b.teacherId