当前位置:   article > 正文

MySQL学习笔记六_sql根据成绩划分等级

sql根据成绩划分等级

一、case when

        case when的用为:从原有数据新增出新的数据

        利用旧数据,形成新的数据进行输出(如:形成新的分类进行输出)

需求:根据成绩分等级,成绩<60的为C等,成绩在[60,80]为B等,成绩>80为A等

        这里的等级用case来设置输出,case when ... then... when...then...else...end

  1. select sid,(case
  2. when score<60 then 'C'
  3. when score>=60 and score<=80 then 'B'
  4. else 'A'
  5. end) as level
  6. from sc;

        上面是用case when来根据成绩输出等级,那么如何一步到位对等级进行计数呢,可以利用sum/count + case when,每一个等级利用一次case when及聚合函数,三个等级利用三次

需求:根据成绩划分等级并根据等级计数

        记得每个case要有一个end做结尾

  1. select sum(case when score<60 then 1 else 0 end) as C,
  2. sum(case when score>=60 and score<=80 then 1 else 0 end) as B
  3. count(case when score>80 then 1 else null end) as A
  4. from sc;

二、保存结果表-as/like

        数据的持久化:as是直接复制,like是复制表结构

1.as-直接复制

        create table tablename as ...    这里...是一个表结果输出,不能是一个表

  1. drop table if exists `re1`;
  2. create table re1 as
  3. select sum(case when score<60 then 1 else 0 end) as C,
  4. sum(case when score>=60 and score<=80 then 1 else 0 end) as B
  5. count(case when score>80 then 1 else null end) as A
  6. from sc;
  7. drop table if exists `sc2`;
  8. create table sc2 as
  9. select * from sc;

2.like-复制表结构

        create table tablename like  tablename    这里tablename是一个实体表,不能是一个结果

  1. drop table if exists commodity;
  2. create table commoditytype like ishop1.commoditytype;

三、触发器

        监控表,当被监控的表的数据发生变化时自动执行某SQL语句,此时用到了触发器。

        触发器的应用场景:①每当增加一个顾客到某个数据表时,需要检查他的电话号码格式是否正确;②每当增加一个订单时,从库存中减去相应的数量;③无论何时删除一行,都在某个数据表中保留一个副本。

        即上述的例子都是需要在某个表发生更改时自动处理。

        delete、insert、update语句支持触发器,自动执行一条SQL语句,其他语句不支持触发器。

        创建触发器要素:唯一的触发器名称、触发器关联的表(被监控的表)、触发器响应的活动(insert、delete、updateÿ

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/931496
推荐阅读
相关标签
  

闽ICP备14008679号