赞
踩
case when的用为:从原有数据新增出新的数据
利用旧数据,形成新的数据进行输出(如:形成新的分类进行输出)
这里的等级用case来设置输出,case when ... then... when...then...else...end
- select sid,(case
- when score<60 then 'C'
- when score>=60 and score<=80 then 'B'
- else 'A'
- end) as level
- from sc;
上面是用case when来根据成绩输出等级,那么如何一步到位对等级进行计数呢,可以利用sum/count + case when,每一个等级利用一次case when及聚合函数,三个等级利用三次
记得每个case要有一个end做结尾
- select sum(case when score<60 then 1 else 0 end) as C,
- sum(case when score>=60 and score<=80 then 1 else 0 end) as B
- count(case when score>80 then 1 else null end) as A
- from sc;
数据的持久化:as是直接复制,like是复制表结构
create table tablename as ... 这里...是一个表结果输出,不能是一个表
- drop table if exists `re1`;
- create table re1 as
- select sum(case when score<60 then 1 else 0 end) as C,
- sum(case when score>=60 and score<=80 then 1 else 0 end) as B
- count(case when score>80 then 1 else null end) as A
- from sc;
-
- drop table if exists `sc2`;
- create table sc2 as
- select * from sc;
create table tablename like tablename 这里tablename是一个实体表,不能是一个结果
- drop table if exists commodity;
- create table commoditytype like ishop1.commoditytype;
监控表,当被监控的表的数据发生变化时自动执行某SQL语句,此时用到了触发器。
触发器的应用场景:①每当增加一个顾客到某个数据表时,需要检查他的电话号码格式是否正确;②每当增加一个订单时,从库存中减去相应的数量;③无论何时删除一行,都在某个数据表中保留一个副本。
即上述的例子都是需要在某个表发生更改时自动处理。
delete、insert、update语句支持触发器,自动执行一条SQL语句,其他语句不支持触发器。
创建触发器要素:唯一的触发器名称、触发器关联的表(被监控的表)、触发器响应的活动(insert、delete、updateÿ
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。