我想使用案例查询总标记列并获取各自等级的标记并将其存储为单独的列。我现在已经尝试了一段时间,但它一直给我错误。
SELECT gradecalc.StudentId,gradecalc.CourseCode, Total,
CASE TOTAL
WHEN >90 THEN 'AA'
WHEN <90 AND >85 THEN 'BA'
WHEN <85 AND >=80 THEN 'BB'
WHEN <80 AND >=75 THEN 'CB'
WHEN <75 AND >=70 THEN 'CC'
WHEN <70 AND >=65 THEN 'DC'
WHEN <65 AND >=60 THEN 'DD'
ELSE 'FF'
END AS Grade
FROM GRADECALC GROUP BY gradecalc.StudentId,gradecalc.CourseCode
答案 0 :(得分:1)
你可以试试这个,交配:
SELECT
gc.StudentId,
gc.CourseCode,
gc.Total,
CASE
WHEN gc.Total > 90 THEN 'AA'
WHEN gc.Total BETWEEN 85 AND 90 THEN 'BA'
WHEN gc.Total BETWEEN 80 AND 85 THEN 'BB'
WHEN gc.Total BETWEEN 75 AND 80 THEN 'CB'
WHEN gc.Total BETWEEN 70 AND 75 THEN 'CC'
WHEN gc.Total BETWEEN 65 AND 70 THEN 'DC'
WHEN gc.Total BETWEEN 60 AND 65 THEN 'DD'
ELSE 'FF'
END AS Grade
FROM
gradecalc gc
GROUP BY
gc.StudentId, gc.CourseCode;
答案 1 :(得分:0)
case <column> when <value>
语法只能处理相等性检查。对于其他运算符,您必须使用稍微不同的语法:
SELECT gradecalc.StudentId,gradecalc.CourseCode, Total,
CASE
WHEN total > 90 THEN 'AA'
WHEN total < 90 AND total >= 85 THEN 'BA'
WHEN total < 85 AND total >= 80 THEN 'BB'
WHEN total < 80 AND total >=75 THEN 'CB'
WHEN total < 75 AND total >=70 THEN 'CC'
WHEN total < 70 AND total >=65 THEN 'DC'
WHEN total < 65 AND total >=60 THEN 'DD'
ELSE 'FF'
END AS Grade
FROM GRADECALC GROUP BY gradecalc.StudentId,gradecalc.CourseCode
答案 2 :(得分:0)
您需要将完整的表达式放在case when
中。您的case <variable> when <constant>
语法仅适用于常量。
现在,您还可以简化表达式,因为case
按顺序处理。所以这是等价的逻辑:
SELECT gc.StudentId, gc.CourseCode, gc.Total,
(CASE WHEN TOTAL > 90 THEN 'AA'
WHEN TOTAL > 85 THEN 'BA'
WHEN TOTAL >= 80 THEN 'BB'
WHEN TOTAL >= 75 THEN 'CB'
WHEN TOTAL >= 70 THEN 'CC'
WHEN TOTAL >= 65 THEN 'DC'
WHEN TOTAL >= 60 THEN 'DD'
ELSE 'FF'
END) AS Grade
FROM GRADECALC gc
GROUP BY gc.StudentId, gc.CourseCode ;
我不认为GROUP BY
是必要的,除非你有一个给定学生和课程的多行。如果您这样做,那么您可能希望在AVG(Total)
声明中使用case
或类似内容。
通过这种表述,您可以很容易地看到“90”和“85”是可疑的。事实上,你原来的逻辑会给学生这些标记一个“FF”,我猜这不是意图。
所以:
SELECT gc.StudentId, gc.CourseCode, gc.Total,
(CASE WHEN TOTAL >= 90 THEN 'AA'
WHEN TOTAL >= 85 THEN 'BA'
WHEN TOTAL >= 80 THEN 'BB'
WHEN TOTAL >= 75 THEN 'CB'
WHEN TOTAL >= 70 THEN 'CC'
WHEN TOTAL >= 65 THEN 'DC'
WHEN TOTAL >= 60 THEN 'DD'
ELSE 'FF'
END) AS Grade
FROM GRADECALC gc;