2012-10-22 36 views
0

嗨,我有一张表,用于存储字段stu_score中不同主题的学生成绩。主题在字段ex_subjects中,我需要查询表格,以便将分数排列为每个主题的单独列。我已成功地查询数学喜欢:在Oracle 10g中将行值作为不同列查询

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 

的输出继电器是

DB Screenshot

我需要在表中的其他科目,如ENGLISHPHYSICSCHEMISTRY一样..... 解决这个问题的最佳方法是什么?

+1

你的意思是你想新列添加到结果,与得分为其他科目?我的意思是你想看一个结果集中所有主题的所有分数吗? – ppeterka

+0

是在一个结果集中...该示例只有数学 – ErrorNotFoundException

回答

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 
+1

嘿,我比我更喜欢这个! – ppeterka

+0

其实这是正确的......我认为这就是我一直在寻找....有没有一种方法来零价值为零的所有地方? – ErrorNotFoundException

+2

@Stanley:使用0而不是null的最简单方法是在'case'表达式的'end'之前包含'else 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 

注:我用的顺序改变了,在这种形式是不再可用,现在这个总结分数,然后排名。

但是,这个确切的DB结构是不好的。这不是在First Normal Form (1NF),这使事情不必要的困难,并容易出错。另外请考虑阅读2NF3NFBCNF(其他人也是,但AFAIK,这些是更广泛已知和使用的正常形式)。我假设你正在学习,这会让你走上正轨。

你应该把你的一个表分成(至少)两个:一个用于学生的个人数据(现在用于MAIN别名的列),另一个用于分数(其他列)。

+1

+1用于规范化。 –

+0

我不确定为什么,但是这个查询不返回任何值。 – ErrorNotFoundException