2013-03-12 99 views
-1

我是SQL新手,希望能够通过以下查询获得一些帮助。SQL从2个表中选择条件

我有3个表:

  • 学生(姓名,student_id数据);
  • exam_results(module_code,student_id,grade);
  • 项目(module_code,student_id,等级)。

我想选择学生姓名,成绩和module_code,但是有些模块同时考试和与他们相关的项目。所以如果是这样的话,我希望成为项目和考试的平均分,否则就是考试成绩。

任何想法?

+0

http://mattgemmell.com/2008/12/08/what-have-you-tried/ – 2013-03-12 14:05:43

+0

@BradM我觉得输入http://www.whathaveyoutried.com时要短一些 – Kermit 2013-03-12 14:06:07

回答

1
SELECT s.student_id, s.name, m.module_code, avg(m.grade) as grade from students s 
inner join 
(select module_code, student_id, grade from exam_results 
union all select module_code, student_id, grade from projects) as exam_module m 
on s.student_id = m.student_id 
group by s.student_id, s.name, m.module_code