将学生成绩转换成各自的成绩

时间:2019-06-30 09:52:51

标签: sql oracle

需要查询以为letter_grade表中的每个记录打印与学生的max_grade相关的StudentStudent 1 has grade: A Student 2 has grade: C Student 3 has grade: B Student 4 has grade: F But I'm not sure how to pass "id" value into the then clause. Below is the code I have implemented : select CASE WHEN max_grade < 20 then "Student id has grade: F" WHEN (max_grade >=20 AND max_grade <40) then "Student id has grade: D" WHEN (max_grade >=40 AND max_grade <60) then "Student id has grade: C" WHEN (max_grade >=60 AND max_grade <80) then "Student id has grade: B" ELSE "Student id has grade: A" END AS Grade_details from students order by id; 。输出必须按升序排列,并应遵循以下格式:

nifty([], []).
nifty([[]|X], []) :-
   nifty(X, []).
nifty([], [[]|X]) :-
   nifty([], X).
nifty([[X|Y]|Z], [[X|Q]|R]) :-
   swap(Y, R, N),
   swap(Q, Z, M),
   nifty(M, N).

swap([], [], []).
swap([X|Y], [[X|P]|Q], [P|R]) :-
   swap(Y, Q, R).

4 个答案:

答案 0 :(得分:2)

您需要在短语中连接ID和字母等级:

'Student ? has grade: ?' 

与此:

select 
 'Student ' || id ' has grade: ' || CASE 
    WHEN max_grade < 20 then 'F' 
    WHEN max_grade < 40 then 'D'
    WHEN max_grade < 60 then 'C'
    WHEN max_grade < 80 then 'B'
    ELSE 'A'
  END AS Grade_details 
FROM students 
ORDER BY id;

答案 1 :(得分:1)

您可以在sql查询中使用大小写条件将标记转换为等级

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

请参阅此link以了解案例说明。

SELECT studentID, CASE statement FROM table name ORDER BY studentID

使用order by语句,您可以按升序或降序获得输出

答案 2 :(得分:0)

您可以直接使用case逻辑:

select (case when max_grade < 20 then 'F'
             when max_grade < 40 then 'D'
             when max_grade < 60 then 'C'
             when max_grade < 80 then 'B'
             else 'A'
        end) as letter_grade

请注意,case表达式返回第一个匹配表达式,因此仅需要上限。此版本假定max_grade不是null

还请注意,此版本为最高正好为80的学生分配字母等级。

答案 3 :(得分:0)

我们需要设置“ sql_mode”(对于MySql数据库)

SET sql_mode = 'PIPES_AS_CONCAT';

select 
    CASE
        when max_grade<20 then 'Student '||id||' has grade: F'
        when max_grade>=20 and max_grade<40 then 'Student '||id||'  has grade: D'
        when max_grade>=40 and max_grade<60 then 'Student '||id||'  has grade: C'
        when max_grade>=60 and max_grade<80 then 'Student '||id||' has grade: B'
        when max_grade>=80 then 'Student  '||id||' has grade: A'
    END AS letter_grade
from student order by ID;