0

こんにちはみんなフィールドのさまざまな科目の学生のスコアを保存する1つのテーブルがあります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

クエリをよく理解していれば、DB 構造を変更せずにこれを行うことができます。

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 構造は不適切です。これは第 1 正規形 (1NF)ではないため、物事が不必要に難しくなり、エラーが発生しやすくなります。また、 2NF3NF、およびBCNFも読むことを検討してください(他のものもそうですが、知る限り、これらはより広く知られ、使用されている正規形です)。私はあなたが学んでいると仮定します、そしてこれはあなたを正しい軌道に乗せるでしょう.

1 つのテーブルを (少なくとも) 2 つに分割する必要があります。1 つは学生の個人データ用 (現在 MAIN エイリアスで使用される列) で、もう 1 つはスコア用 (その他の列) です。

于 2012-10-22T11:09:57.510 に答える
2

テーブルへのアクセスが 1 回だけ必要なクエリの場合は、次を試してください。

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 に答える