2014-05-12 64 views
0

我遇到了較大查詢的一部分問題。我需要在今年年底獲得學生最近的GPA。這取決於他們上課的最近學期。 GPA通過術語摘要存儲在數據庫中,而不是滾動式GPA。我在爲每個學生抓取最近的學期入學條款方面存在問題。我的查詢在下方,我需要知道如何拉最近的gpa,但每個學生最近一次參加該學年。僅供參考我正在使用SQL Server。按學生最近學期查詢ID#和GPA

SELECT s.id, 
    Max (t.terms), 
    Max(t.gpa), 
    Sum(s.credits) AS systemCredits, 
    Sum(s2.credits) AS DegreeCredits, 
    Sum (s3.credits) AS trans_in 
FROM (SELECT * 
    FROM student_courses 
    WHERE (course_code IN ('a', 'b', 'c')) 
      AND grade IN ('a', 'b', 'c')) s 
    FULL OUTER JOIN (SELECT * 
        FROM student_crs_hist 
        WHERE (course_code IN ('a', 'b', 'c')) 
          AND grade IN ('a', 'b', 'c')) s2 
       ON s.id = s2.id 
        AND s.years = s2.years 
        AND s.terms = s2.terms 
    JOIN (SELECT * 
     FROM stud_term_sum_div 
     WHERE years = '2013' 
       AND terms = (SELECT Max(terms) 
          FROM term_sum 
          WHERE years = '2013')) t 
    ON s.id = t.id 
    GROUP BY s.id 

回答

1

如果沒有完全理解數據模型可能帶來的挑戰,我會建議將其分解爲多個查詢。

第一個查詢應確定每名學生參加了最近的學期,並將其存儲在某個地方方便,就像變量表

declare @recentSemester 
table (semesterId int 
     , studentId int) 

insert into @recentSemester 
select 
    studentId 
    , max(semesterId) 
from student_courses sc 
left join student_crs_hist sch 
    on sc.id = sch.id 
where sch.course_code in ('a', 'b', 'c') 
    and sch.grade in ('a', 'b', 'c') 
group by studentId 

第二個查詢應直接對存儲表加入這個表變量您學期GPA和執行任何聚合。