问题场景
我们常常会遇到这样的场景,如果有学生的分数,如何根据分数给学生打等级?
id | name | score |
1 | 猪头 | 85.5 |
2 | 猪猪侠 | 99.99 |
3 | 猪八戒 | 75.5 |
4 | 猪悟能 | 55.5 |
我们想给上面的学生根据评分规则,打上等级,譬如,评分规则
- 分数在90-100,A+
- 分数在85-90,A
- 分数在75-85,B+
- 分数在60-75,B
- 分数在60一下,B-
我们想最后通过上面的评分规则,自动打分,最终形成下面的表格
id | name | score | ranking |
1 | 猪头 | 85.5 | A |
2 | 猪猪侠 | 99.99 | A+ |
3 | 猪八戒 | 75.5 | B+ |
4 | 猪悟能 | 55.5 | B- |
解决方案
我们可以使用下面的命令,先进行查询
select *,
case
when score<60.0 then'B-'
when score>=60.0 and score<75.0 then 'B'
when score>=75.0 and score<85.0 then 'B+'
when score>=85.0 and score<90.0 then 'A'
when score>=90.0 and score<=100.0 then 'A+'
end ranking
from fancypig
然后你可以看到表里已经构造出了新的ranking字段,并按要求打上了等级
如果上面的测试没问题了,那么我们直接更新字段就好了!
我们这里输入下面的命令
update fancypig
set ranking =
case
when score<60.0 then'B-'
when score>=60.0 and score<75.0 then 'B'
when score>=75.0 and score<85.0 then 'B+'
when score>=85.0 and score<90.0 then 'A'
when score>=90.0 and score<=100.0 then 'A+'
else ranking end
场景应用
我这里有6W多条漏洞信息,但是很多都没有等级,因此,我需要给它打上等级,使用下面的语句
update plugins set risk =
case
when cvss=0.0 then'None'
when cvss>0.0 and cvss<=3.9 then 'Low'
when cvss>=4.0 and cvss<=6.9 then 'Medium'
when cvss>=7.0 and cvss<=8.9 then 'High'
when cvss>=9.0 and cvss<=10.0 then 'Critical'
else risk end
瞬间更新3W条,简直舒服到爆炸😄😄
![图片[1]-Mysql如何根据字段中的评分打等级 生成新的等级字段?-FancyPig's blog](https://static.iculture.cc/wp-content/uploads/2022/02/20220224122322239.png?x-oss-process=image/auto-orient,1/format,webp/watermark,image_cHVibGljL2xvZ28ucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMTA,x_10,y_10)
© 版权声明
THE END
- 最新
- 最热
只看作者