首页 > 数据库技术 > 详细

sql case 函数与详细说明

时间:2017-02-20 18:47:42      阅读:245      评论:0      收藏:0      [点我收藏+]

下面是一个是用case函数来完成这个功能的例子

case具有两种格式。简单case函数和case搜索函数。 
--简单case函数

case sex
         when ‘1‘ then ‘男‘
         when ‘2‘ then ‘女‘
else ‘其他‘ end
--case搜索函数
case when sex = ‘1‘ then ‘男‘
         when sex = ‘2‘ then ‘女‘
else ‘其他‘ end

这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判断式。 
还有一个需要注意的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。 
--比如说,下面这段sql,你永远无法得到“第二类”这个结果

case when col_1 in ( ‘a‘, ‘b‘) then ‘第一类‘
         when col_1 in (‘a‘)       then ‘第二类‘
else‘其他‘ end


下面看一些实例

select country, 
sum( case when sex = ‘1‘ then 
population else 0 end), --男性人口 
sum( case when sex = ‘2‘ then 
population else 0 end) --女性人口 
from table_a 
group by country;


select sum(population), 
case country 
when ‘中国‘ then ‘亚洲‘ 
when ‘印度‘ then ‘亚洲‘ 
when ‘日本‘ then ‘亚洲‘ 
when ‘美国‘ then ‘北美洲‘ 
when ‘加拿大‘ then ‘北美洲‘ 
when ‘墨西哥‘ then ‘北美洲‘ 
else ‘其他‘ end 
from table_a 
group by case country 
when ‘中国‘ then ‘亚洲‘ 
when ‘印度‘ then ‘亚洲‘ 
when ‘日本‘ then ‘亚洲‘ 
when ‘美国‘ then ‘北美洲‘ 
when ‘加拿大‘ then ‘北美洲‘ 
when ‘墨西哥‘ then ‘北美洲‘ 
else ‘其他‘ end;

关于case 二

select 
case when salary <= 500 then ‘1‘ 
when salary > 500 and salary <= 600 then ‘2‘ 
when salary > 600 and salary <= 800 then ‘3‘ 
when salary > 800 and salary <= 1000 then ‘4‘ 
else null end salary_class, 
count(*) 
from table_a 
group by 
case when salary <= 500 then ‘1‘ 
when salary > 500 and salary <= 600 then ‘2‘ 
when salary > 600 and salary <= 800 then ‘3‘ 
when salary > 800 and salary <= 1000 then ‘4‘ 
else null end;
mysq中横表和纵表的转换有时也是用这种 方法来转换 http://blog.csdn.net/fysuccess/article/details/40789869

 case when 是静态的转换方法,肯定不适合大量动态数据的查询,新的查询方法如下  http://qianzhang.blog.51cto.com/317608/1202793

sql case 函数与详细说明

原文:http://www.cnblogs.com/xs-yqz/p/6420672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!