如何从一个表中选择一个记录,并计算出另一个表的数量并对其进行计数

时间:2013-07-09 07:08:44

标签: sql oracle

我在拖车台下方 表1:教师表

teacher_id   teacher_name
1            xx
2            yy
3            zz

表2:学生表

stu_id       stu_name     tearcher1_id     teacher2_id    tearcher3_id
1            aa           1                2 
2            bb           2                3
3            cc           1

我希望从教师那里得到一个sql语句列表,其中包括谁出现在学生表中的计数如下:

teacher_id      teacher_name          num_selected_by_stu
1               xx                    2
2               yy                    2
3               zz                    1

我在sql下面试过但似乎不行,

    select * from teatcher t1 
    left join (
    select stu_id,tearcher1_id,tearcher2_id,tearcher3_id,count(stu_id) as num_selected_by_stu from student 
    group by stu_id,tearcher1_id,tearcher2_id,tearcher3_id) t2 
    ON ( t2.teacher1_id=t1.teacher_id or t2.teacher2_id=t1.teacher_id or t2.teacher3_id=t1.teacher_id)

并且,任何人都可以提供帮助吗?

3 个答案:

答案 0 :(得分:1)

SELECT 
  teacher_id
  teacher_name
  NVL(num1, 0) + NVL(num2, 0) + NVL(num3,0) as num_selected_by_stu
FROM 
  teacher t
  left outer join ( SELECT count(*) as num1, tearcher1_id FROM student group by tearcher1_id ) t1 on t1.tearcher1_id = t.tearcher_id
  left outer join ( SELECT count(*) as num2, tearcher2_id FROM student group by tearcher2_id ) t2 on t2.tearcher2_id = t.tearcher_id
  left outer join ( SELECT count(*) as num3, tearcher3_id FROM student group by tearcher3_id ) t3 on t3.tearcher3_id = t.tearcher_id
;

答案 1 :(得分:0)

请尝试:

SELECT 
    *,
    (SELECT 
        COUNT(*) 
    FROM 
        Student t2 
    WHERE 
        t1.teacher_id=t2.tearcher1_id OR 
        t1.teacher_id=t2.teacher2_id OR 
        t1.teacher_id=t2.tearcher3_id) num_selected_by_stu
FROM 
    Teacher t1

答案 2 :(得分:0)

select t.teacher_id,t.teacher_name from teacher t ,

inner join student s
 on t.teacher_id = s.teacher_id
 where 
 case when teacher1_id < 35  then 0 else 1 end +
 case when teacher1_id < 35  then 0 else 1 end +
 case when teacher1_id < 35  then 0 else 1 end +
 end 
 as [num_selected_by_stu]