SQL获得成绩

时间:2014-11-06 10:52:28

标签: sql

我正在创建一个存储测试的应用程序。数据库模式简化如下

id_student            id_teacher          grade second_test

student_1             teacher_1           10    'Y'
student_1             teacher_1           5     'N'
student_2             teacher_1           8     'N'
student_3             teacher_1           9     'N'

我需要一个查询来获得每个学生的成绩,考虑到如果该学生进行了第二次测试(这是一个检索),则返回的等级必须是第二次测试(而不是第一次)。

因此,对于该示例,结果集应为

student_1             teacher_1           10    'Y'
student_2             teacher_1           8     'N'
student_3             teacher_1           9     'N'

我写了一个sql,但它没有用。因为它无法获得student_2和student_3

SELECT
  m.id_student,
  m.grade
FROM
  mytable m
WHERE
  second_test = 'Y'
  OR EXISTS (
    SELECT 1
    FROM
      mytable
    WHERE
      id_student = m.id_student
      AND id_teacher <> m.id_teacher
      AND second_test = 'Y'
)

2 个答案:

答案 0 :(得分:1)

如果一个学生在你的桌子上只能有一个或两个记录,你可以将第一个测试加入第二个测试。

select 
    t1.id_student,
    t1.id_teacher,
    coalesce(t2.grade,t1.grade)
from
    (select id_student, id_teacher, grade from my_table where second_test = 'N') as t1
left join
    (select id_student, id_teacher, grade from my_table where second_test = 'Y') as t2
on 
    t1.id_student = t2.id_student and t1.id_teacher = t2.id_teacher

如果一个学生的测试记录超过两个,那么你应该在这两个子查询中使用聚合方法。

答案 1 :(得分:1)

你走了。 首先,让所有具有两个年级的学生从第二个考试中取出一个,然后将其与只有一个年级的学生联合起来。

SELECT
    a.id_student, a.id_teacher, b.grade, b.second_test
FROM (
    SELECT
        id_student, id_teacher
    FROM
        mytable
    GROUP BY 1,2
    HAVING COUNT(*) > 1
    ) a
    JOIN mytable b ON a.id_student = b.id_student AND a.id_teacher = b.id_teacher AND b.second_test = 'Y'
UNION
SELECT
    a.id_student, a.id_teacher, b.grade, b.second_test
FROM (
    SELECT 
        id_student, id_teacher
    FROM
        mytable
    GROUP BY 1,2
    HAVING COUNT(*) = 1
    ) a
    JOIN mytable b ON a.id_student = b.id_student AND a.id_teacher = b.id_teacher

即使您每个学生有5个等级(取决于旗帜),也可以轻松修改此答案以获得最新成绩。