嗨,大家好我有一张桌子,用于存储现场stu_score
中不同主题的学生成绩。主题位于字段ex_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
.....
解决这个问题的最佳方式是什么?
答案 0 :(得分: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
注意:我改变了顺序,因为在那种形式中它不再可用,现在它将得分相加,并按此排名。
但是,这种确切的数据库结构很糟糕。这不在First Normal Form (1NF)中,这会使事情变得不必要,并且容易出错。另外,请考虑阅读2NF,3NF和BCNF(其他也是如此,但AFAIK,这些是更广为人知和使用的普通形式)。我假设你正在学习,这将使你走上正确的轨道。
您应该将您的一个表分成(至少)两个:一个用于学生的个人数据(现在与MAIN别名一起使用的列),一个用于分数(其他列)。
答案 1 :(得分: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