2014-05-12 34 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和执行任何聚合。