2013-03-12 92 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