首先我们来看Oracle一个函数decode(条件,值1,翻译值1,值2,翻译值2…)
和case 条件 when 值1 then 返回值1 when 值2 then 返回值2…语句
Mysql的操作大同小异
例子如下:
--sal*1.1和sal*1.2可以替换为
--一个具体的数字或是其他字段的字段名
--也可以是其他字段名的计算表达式
select ename,sal,deptno,decode(deptno,10,sal*1.1,20,sal*1.2) from emp;
上面decode相当于
if(deptno == 10)
sal *= 1.1;
else if(deptno == 20)
sal *= 1.2;
对每个符合条件的sal进行对应修改并作为结果显示出来
上面查询会显示4列结果分别是ename,sal,deptno,decode(sal)
而如果用case when语句则写法如下
select ename,
sal,
deptno,
case deptno
when 10 then
sal * 1.1
when 20 then
sal * 1.2
end
from emp;
知道有上面的操作后假设有个这样的test表:
我们要把它转换成:
姓名 | 性别 | 年龄 |
---|---|---|
张三 | 男 | 50 |
刘二 | 男 | 30 |
刘三 | 女 | 10 |
用decode处理表格后结果如下:
--value表示值本身,可以对value进行操作,也可什么都不做
--type是字段名
select decode(type,1,value) as 姓名,
decode(type,2,value) as 性别,
decode(type,3,value) as 年龄,
from test;
用decode配合组函数(如:max())后多行汇聚成了一行:
select max(decode(type,1,value)) as 姓名,
max(decode(type,2,value)) as 性别,
max(decode(type,3,value)) as 年龄,
from test;
最后我们利用test表的t_id对结果进行分组:
select max(decode(type,1,value)) as 姓名,
max(decode(type,2,value)) as 性别,
max(decode(type,3,value)) as 年龄,
from test group by t_id;
我们得到想要的结果了!!!
除了上面的decode和case when方法还可以用 子查询+表连接 以及 union all+字段占位的方法进行 行转列,但是就效率上来说decode和case when的方法效率最高