SQL之case when then用法详解
来源:互联网 发布:部分便笺元数据已损坏 编辑:程序博客网 时间:2024/06/16 23:39
case具有两种格式。简单case函数和case搜索函数。
<span style="font-size:14px;">--简单case函数 case sex when '1' then '男' when '2' then '女’ else '其他' end --case搜索函数 case when sex = '1' then '男' when sex = '2' then '女' else '其他' end</span>
这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。
还有一个需要注重的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略
<span style="font-size:14px;">--比如说,下面这段sql,你永远无法得到“第二类”这个结果 case when col_1 in ('a','b') then '第一类' when col_1 in ('a') then '第二类' else '其他' end </span>
实例演示:
首先创建一张users表,其中包含id,name,sex三个字段,表内容如下:
<span style="font-size:14px;">select * from users </span>
1 张一
2 张二 1
3 张三
4 张四
5 张五 2
6 张六 1
7 张七 2
8 张八 1
1、上表结果中的”sex”是用代码表示的,希望将代码用中文表示。可在语句中使用case语句:
<span style="font-size:14px;">select u.id,u.name,u.sex, (case u.sex when 1 then '男' when 2 then '女' else '空的' end )性别 from users u;</span>
ID NAME SEX 性别
1 张一 空的 2 张二 1 男 3 张三 空的 4 张四 空的 5 张五 2 女 6 张六 1 男 7 张七 2 女 8 张八 1 男
2、如果不希望列表中出现”sex”列,语句如下:
select u.id,u.name, (case u.sex when 1 then '男' when 2 then '女' else '空的' end )性别 from users u;
ID NAME 性别
1 张一 空的 2 张二 男 3 张三 空的 4 张四 空的 5 张五 女 6 张六 男 7 张七 女 8 张八 男
3、将sum与case结合使用,可以实现分段统计。
如果现在希望将上表中各种性别的人数进行统计,sql语句如下:
select sum(case u.sex when 1 then 1 else 0 end)男性, sum(case u.sex when 2 then 1 else 0 end)女性, sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性别为空 from users u;
男性 女性 性别为空
3 2 0
SQL> select count(case when u.sex=1 then 1 end)男性, count(case when u.sex=2 then 1 end)女, count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空 from users u;
男性 女 性别为空
3 2 0
阅读全文
0 0
- SQL之case when then用法详解
- SQL之case when then用法详解
- SQL之case when then用法
- SQL之case when then用法
- SQL之case when then用法
- SQL之case when then用法
- SQL之case when then用法
- SQL之case when then用法
- SQL之case when then用法
- SQL之 case when then
- SQL之CASE,WHEN,THEN
- SQL之CASE,WHEN,THEN
- sql学习之CASE WHEN THEN ELSE END的用法
- SQL查询之case when then的用法
- SQL之case when then else end用法
- SQL case when then end 简单用法
- sql中case when then简单用法
- sql case when then end 用法
- 进程资源
- 高新面试系列 性格篇
- Linux install googletest
- Spring 4 官方文档学习(①)Web MVC 框架之异常处理
- 游戏编程中的人工智能 补
- SQL之case when then用法详解
- http的抓包工具
- 20170602学习笔记整理
- 上传文件名称回显
- Linux下MongoDB 安装配置详解
- org.apache.shiro.crypto.CryptoException: Unable to execute 'doFinal' with cipher instance
- java中static{}语句块详解
- Java小案例——判断所给年份是平年还是闰年
- 小P寻宝记---粗心的基友(01背包)