2016-11-05 55 views
-1

3表:如何構建查詢?任何想法?

馬克表:

student_id sa_id marks 
1   1 75 
1   2 80 
1   3 100 
2   4 85 
2   5 90 
2   6 60 

當然表:

course_code sat_id name_code 
AAA 100   1  midterm1 
AAA 100   2  midterm2 
AAA 100   3  final 
BBB 200   4  midterm1 
BBB 200   5  midterm2 
BBB 200   6  final 

變換表:

sa_id  sat_id 
1   1 
2   2 
3   3 
4   4 
5   5 
6   6  
select course.course_code, mark.marks 
from mark 
    left outer join transform on transform.sa_id = mark.sa_id 
    left outer join course on course.sat_id = transfrom.sat_id 
where course.name_code = 'midterm1' 

在上面的查詢只midterm1結果,我們也可以提取MID2和最終

select mark.student_id,course.course_code, mark.marks, course.name_code 
from mark 
    left outer join transform on transform.sa_id = mark.sa_id 
    left outer join course on course.sat_id = transfrom.sat_id 
order by mark.student_id, course.course_code 

結果會給:

student_id course_code marks name_code 
1   AAA 100  75  midterm1 
1   AAA 100  80  midterm2 
1   AAA 100  100 final 
2   BBB 200  85  midterm1 
2   BBB 200  90  midterm2 
2   BBB 200  60  final 

因此,如何建立查詢,應該是

student_id course_code midterm1 midterm2 final 
1    AAA 100  75   80  100 
2    BBB 200  85   90  60 
+0

@scaisEdge爲什麼你使用max?使用它很重要嗎? – jaraisyn

+0

這很重要,因爲您必須按'student_id'分組。無論何時你分組,在SELECT中你只能按GROUP BY中的列進行分組,否則你必須使用像MAX()這樣的集合函數。你知道每個組只有一列,但Oracle不知道,如果你沒有使用聚合函數,它會發出抱怨(給出錯誤)。 – mathguy

回答

1

您可以使用情況時,按組(和一個假的聚合功能)

select 
     student_id 
    , course_code 
    , max(case when name_code ='midterm1' then mark else null) midterm1 
    , max(case when name_code ='midterm2' then mark else null) midterm2  
    , max(case when name_code ='final' then mark else null) final 
from mark 
left outer join transform on transform.sa_id = mark.sa_id 
left outer join course on course.sat_id = transfrom.sat_id 
group by student_id, course_code 
order by mark.student_id, course.course_code 

但是,如果你不喜歡聚集函數的,你可以使用一個3 seleft加入上標記

select 
     mm1.student_id 
     , mm1.course_code 
     , mm1.mark midterm1 
     , mm2.mark midterm2 
     , mm3.mark finale  
    from mark as mm1 
    left join mark as mm2 on mm1.student_id = mm2.student_id and mm1.course_code = mm2.course_code 
    left join mark as mm3 on mm1.student_id = mm3.student_id and mm1.course_code = mm3.course_code 
    left outer join transform on transform.sa_id = mm1.sa_id 
    left outer join course on course.sat_id = transfrom.sat_id 
    where mm1.name_code = 'midterm1' 
    and mm2.name_code = 'midterm2' 
    and mm3.name_code = 'final' 
+0

但我需要沒有最大使用,它不正確使用 – jaraisyn

+0

@ jaraisyn max(..)是一個虛擬函數,僅用於利用基於GROUP BY的分組功能,在這種情況下,您可以獲得對於數值之間的每個關係,單行都是單行的(否則,您將擁有與對應關係一樣多的行):所以這是一個虛擬函數,不會產生附帶損害,但可以減少結果行的數量 – scaisEdge

+0

yeap,i知道你在說什麼,但是學生不知道這標誌着哪一個學期和哪一年。如果我們添加'哪裏'將顯示錯誤 – jaraisyn