设为首页 加入收藏

TOP

sql case 函数与详细说明
2011-06-12 21:40:20 来源: 作者: 【 】 浏览:408次 评论: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;

sql case 函数与详细说明更多相关文章

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇MySQL的触发器写法 下一篇sql Union All与 UNION ALL语法与..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位