国外做外链常用的网站,七牛云存储wordpress,红黑配色网站,国外做logo的网站1 case函数的类型case具有两种格式#xff0c;简单case函数和case搜索函数。这两种方式#xff0c;大部分情况下可以实现相同的功能。1.1 简单case函数语法case column
when condition then value
when condition then value
......
else value end;示例case…1 case函数的类型
case具有两种格式简单case函数和case搜索函数。这两种方式大部分情况下可以实现相同的功能。1.1 简单case函数语法
case column
when condition then value
when condition then value
......
else value end;示例
case sex
when 1 then 男
when 2 then 女
else 其他 end;
1.2 case搜索函数语法
case
when condition [,condition] then value
when condition [,condition] then value
......
else value end;示例case when sex 1 then 男 when sex 2 then 女else 其他 end;
简单case 函数重在简洁但是它只适用于这种单字段的单值比较而case 搜索函数的优点在于适用于所有比较(包括多值比较)的情况。例如:
CASEWHEN sex 1 AND age18 THEN 成年男性WHEN sex 2 AND age18 THEN 成年女性ELSE 其他 END;注意CASE函数只返回第一个符合条件的值剩下的CASE部分将会被自动忽略。比如说下面这段SQL你case when type in (a,b) then 第一类 when type in (a) then 第二类 else 其他类 end永远无法得到“第二类”这个结果。2 case行转列case用的比较广泛的功能就是行转列就是将记录行里的数据按条件转换成具体的列。看如下的一个示例数据
create table score(name varchar(10),course varchar(10),scott int);
insert into score values (n张三,n语文,74);
insert into score values (n张三,n数学,83);
insert into score values (n张三,n物理,93);
insert into score values (n李四,n语文,74);
insert into score values (n李四,n数学,84);
insert into score values (n李四,n物理,94);现在我们想实现这样的功能就是将各学科作为单独的列来显示各个学生各科的成绩。我们可以对课程里的记录做如下的行列转换
select name, max(case course when 语文 then scott else 0 end) 语文, max(case course when 数学 then scott else 0 end) 数学,max(case course when 物理 then scott else 0 end) 物理
from score
group by name;结果3 piovt函数行转列如果要实现等同上面的结果
select * from
score pivot( max(scott) for course in (语文,数学,物理)) a;结果其中for后面的是我们即将进行行转列的列部分
in里面的是我们行转列之后的列
max是聚合IN里面的内容也可以是其他聚合函数SUMMINCOUNT等
piovt写法比较固定是case when的一种简略写法。4 批注case是我们在日常工作中使用非常频繁的一个功能可以很好的将我们需要的数据单独的显示在一列里面有助于对数据有个比较清晰的掌握