SQL中的CASE命令

时间:2018-07-07 16:39:10

标签: sql case

我需要你的帮助。我已经用SQL编写了一些代码,而CASE命令却遇到了一些问题。我想输出1表示大于90的等级,2表示大于80的等级,3表示大于70的等级,否则输出4。仔细检查代码后,仍然无法修复。表中的所有记录都有4个值(在ELSE命令中)。请帮我。非常感谢你!

CREATE TABLE student_grades 
(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    number_grade INTEGER,
    fraction_completed REAL
);

INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Winston", 90, 0.805);
INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Winnefer", 95, 0.901);
INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Winsteen", 85, 0.906);
INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Wincifer", 66, 0.7054);
INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Winster", 76, 0.5013);
INSERT INTO student_grades (name, number_grade, fraction_completed)
    VALUES ("Winstonia", 82, 0.9045);

SELECT 
    name, number_grade, 
    ROUND(fraction_completed * 100,0) "percent_completed" 
FROM
    student_grades;

SELECT 
    number_grade 
FROM
    student_grades 
ORDER BY
    number_grade DESC;

SELECT 
    name, number_grade, 
    CASE number_grade
       WHEN number_grade >= 90 THEN 1 
       WHEN number_grade >= 80 THEN 2 
       WHEN number_grade >= 70 THEN 3 
       ELSE 4
    END AS "letter_grade"
FROM 
    student_grades
ORDER BY
    number_grade DESC;

结果是:

enter image description here

2 个答案:

答案 0 :(得分:7)

您正在混合使用CASE的两种不同方式。

一种方法是:

CASE columnname
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ...
END

另一个是:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
END

如果要测试条件,则CASE后不应有列名,因为第一种形式实际上只是以下形式的缩写:

CASE
    WHEN columnname = value1 THEN result1
    WHEN columnname = value2 THEN result2
    ...
END

因此您的代码等效于:

CASE
    WHEN number_grade = number_grade >= 90 THEN 1
    WHEN number_grade = number_grade >= 80 THEN 2
    WHEN number_grade = number_grade >= 70 THEN 3
    ELSE 4
END

正确的语法是:

CASE
    WHEN number_grade >= 90 THEN 1 
    WHEN number_grade >= 80 THEN 2 
    WHEN number_grade >= 70 THEN 3 
    ELSE 4
END as "letter_grade"

答案 1 :(得分:2)

问题是number_grade之后的CASE。尝试删除number_grade,以便您的代码为:

CASE
   WHEN number_grade >= 90 THEN 1 
   WHEN number_grade >= 80 THEN 2 
   WHEN number_grade >= 70 THEN 3 
   ELSE 4