如何在同一行建立连接和自联接

时间:2015-11-17 19:43:10

标签: sql oracle join

情况是这样的:

  1. Teacher PerformanceStudent Performance实体,因此老师和学生可以参加相同课程的分数
  2. 老师可以教学生和老师
  3. 有一个Teaching Relation表,是的,教师和学生都可以出现在考勤列中,但只有教师可以出现在教师栏目中。
  4. 所需的报告表列出了教师的所有表现,以及老师教授的学生和教师的平均表现。
  5. 在我们的系统中,id是数字,我把它作为名字只是为了演示目的。

    教师表现(tb_tp)

    t_id       | score
    ------------------
     JOHN      | 5
     ASHLEY    | 6
     STEVEN    |4.5
    

    学生表现(tb_sp)

          s_id | score
    ------------------
     SCOTT     | 5
     FRANK     | 8
     TIM       | 7
    

    教学关系(tb_tr)

     t_id (teacher) | a_id for attendance id | a_type attendance type
    ------------------------------------------------------------------
     ASHLEY         | JOHN                   | teacher
     ASHLEY         | FRANK                  | student
     ASHLEY         | TIM                    | student
     JOHN           | ASHLEY                 | teacher
     JOHN           | FRANK                  | student
    

    所需报告:

       t_id     | Score| avg_t  AVG score from Teacher | avg_s AVG score from Student
    --------------------------------------------------------------------------
       ASHLEY   |   6  |     (5 from John) /1          | (8 from Frank + 7 from Tim)/2
    --------------------------------------------------------------------------
       JOHN     |   5  |   (6 from ASHLEY) /1          | (8 from Frank) / 1
    

    我们怎样才能实现这一目标?我想两个连接在一起或联合两个查询,但无论哪种方式都不能将结果保持在同一行并且准确

1 个答案:

答案 0 :(得分:0)

我认为你想要的技术是两个带有聚合的外连接。这是我未经测试的传球:

SELECT p.t_id, p.score, scores.avg_teacher_score, scores.avg_student_score
FROM teacher_performance p
JOIN (
  SELECT t_id, AVG( t.score) AS avg_teacher_score, AVG( s.score ) AS avg_student_score
  FROM teaching_relation tr
  LEFT JOIN teacher_performance t ON t.t_id = tr.a_id AND tr.a_type='teacher'
  LEFT JOIN student_performance s ON s.s_id = tr.a_id AND tr.a_type='student'
  ) scores
  ON scores.t_id = p.t_id