1. case..when case..when语句用于按照条件返回查询结果,如当我们想把emp表的工资按照多少分成几个不同的级别,并分别统计各个级别的员工数。SQL语句如下:
select (case
when sal <= 1000 then
'1'
when sal > 1000 and sal <= 2000 then
'2'
when sal > 2000 and sal <= 3000 then
'3'
when sal > 3000 and sal <= 4000 then
'4'
else
'5'
end) as Levels,
count(*)
from emp
group by (case
when sal <= 1000 then
'1'
when sal > 1000 and sal <= 2000 then
'2'
when sal > 2000 and sal <= 3000 then
'3'
when sal > 3000 and sal <= 4000 then
'4'
else
'5'
end) order by levels;
其中,when后可直接跟确定的条件,也可以像上面一样跟表达式。当我们想要使用group..by分组时,要把case..when整个语句放在group by 子句中,不能使用如上面case..when语句的别名"Levels"。
2. decode函数
(1)decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)
当条件等于值1,则返回值2;当条件等于值2,则返回值2...
(2)decode(字段或字段的运算,值1,值2,值3)
select (case
when sal <= 1000 then
'1'
when sal > 1000 and sal <= 2000 then
'2'
when sal > 2000 and sal <= 3000 then
'3'
when sal > 3000 and sal <= 4000 then
'4'
else
'5'
end) as Levels,
count(*)
from emp
group by (case
when sal <= 1000 then
'1'
when sal > 1000 and sal <= 2000 then
'2'
when sal > 2000 and sal <= 3000 then
'3'
when sal > 3000 and sal <= 4000 then
'4'
else
'5'
end) order by levels;
其中,when后可直接跟确定的条件,也可以像上面一样跟表达式。当我们想要使用group..by分组时,要把case..when整个语句放在group by 子句中,不能使用如上面case..when语句的别名"Levels"。
2. decode函数
(1)decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)
当条件等于值1,则返回值2;当条件等于值2,则返回值2...
(2)decode(字段或字段的运算,值1,值2,值3)
当字段或字段的运算等于值1,则返回值2,否则返回值3。
如:有表如下
我们想得到如下的查询结果:
SQL语句如下:
select country,decode(sex,'1','男','2','女') as sex,population from test;
本文介绍了SQL中CASE WHEN语句的应用,展示了如何根据不同条件将数据分为多个等级并进行统计。同时,还讲解了DECODE函数的用法,通过实例演示了如何使用DECODE函数实现条件判断。
297

被折叠的 条评论
为什么被折叠?



