0

嗨,伙计们,我有一张表,用于存储该领域不同科目的学生分数stu_score。主题在 Fieldex_subjects中,我需要查询表格,以便将分数排列为每个主题的单独列。我已经设法查询数学,例如:

select stu_number, stu_name,  ex_name, stu_score as MATHEMATICS 
from EXAMS_MASTER_REGISTER 
where stu_level = '1' and stu_stream = 'EAST' 
and ex_semester = 'FIRST' 
and ex_name = 'MIDYEARS' 
and ex_subject = 'MATHEMATICS' 
and academic_year = '2012' 
order by stu_score desc

输出是

数据库截图

对于表中的其他主题,我需要相同的内容,例如ENGLISH, PHYSICS, CHEMISTRY..... 解决此问题的最佳方法是什么?

4

2 回答 2

2

如果我很好地理解了您的查询,那么可以在不更改数据库结构的情况下这样做:

select MAIN.stu_number, MAIN.stu_name,  MAIN.ex_name, 
    MATHS.stu_score as MATHEMATICS, 
    ENGLISH.stu_score as ENGLISH, 
    PHYSICS.stu_score as PHYSICS, 
    CHEMISTRY.stu_score as CHEMISTRY
from EXAMS_MASTER_REGISTER MAIN
left join EXAMS_MASTER_REGISTER MATHS on MAIN.stu_number = MATHS.stu_number AND MATHS.ex_subject = 'MATHEMATICS'
left join EXAMS_MASTER_REGISTER ENGLISH on MAIN.stu_number = ENGLISH.stu_number AND ENGLISH.ex_subject = 'ENGLISH'
left join EXAMS_MASTER_REGISTER PHYSICS on MAIN.stu_number = PHYSICS.stu_number AND PHYSICS.ex_subject = 'PHYSICS'
left join EXAMS_MASTER_REGISTER CHEMISTRY on MAIN.stu_number = CHEMISTRY.stu_number AND CHEMISTRY.ex_subject = 'CHEMISTRY'
where MAIN.stu_level = '1' 
and MAIN.stu_stream = 'EAST' 
and MAIN.ex_semester = 'FIRST' 
and MAIN.ex_name = 'MIDYEARS' 
and MAIN.academic_year = '2012' 
order by (NVL(MATHS.stu_score,0) + NVL(ENGLISH.stu_score,0) + NVL(PHYSICS.stu_score,0) + NVL(CHEMISTRY.stu_score,0) ) desc

注意:我更改了顺序,因为在那种形式下它不再可用了,现在这对分数求和,然后按那个排序。

但是,这种确切的数据库结构是不好的。这不是第一范式(1NF),这使事情变得不必要地困难并且容易出错。还可以考虑阅读2NF3NFBCNF(其他的也是,但 AFAIK,这些是更广为人知和使用的范式)。我假设您正在学习,这将使您走上正确的轨道。

您应该将一张表分成(至少)两张:一张用于学生的个人数据(现在与 MAIN 别名一起使用的列),一张用于分数(其他列)。

于 2012-10-22T11:09:57.510 回答
2

对于只需要一次访问表的查询,请尝试:

select stu_number, 
       max(stu_name) stu_name, 
       ex_name, 
       max(case when ex_subject = 'MATHEMATICS' then stu_score end) as MATHEMATICS,
       max(case when ex_subject = 'ENGLISH' then stu_score end) as ENGLISH,
       max(case when ex_subject = 'PHYSICS' then stu_score end) as PHYSICS,
       max(case when ex_subject = 'CHEMISTRY' then stu_score end) as CHEMISTRY
from EXAMS_MASTER_REGISTER 
where stu_level = '1' and 
      stu_stream = 'EAST' and 
      ex_semester = 'FIRST' and 
      ex_name = 'MIDYEARS' and 
      academic_year = '2012' 
group by stu_number, ex_name
order by sum(stu_score) desc
于 2012-10-22T11:20:23.447 回答