SQL中case when then用法

本文介绍了SQL中CASE WHEN THEN的两种格式——简单CASE和CASE搜索函数,并通过实例展示了如何在数据转换、条件判断及分段统计等方面应用。案例包括将性别代码转为中文、隐藏特定列以及结合SUM进行分段统计。
摘要由CSDN通过智能技术生成

SQL中case when then用法

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


下面给给例子你就知道他的用法了:

create table student(
	name varchar(20) not null, --姓名
	subject varchar(20) not null,--科目
	result float not null,--成绩
)
--插入数据
insert into student
select '张三','语文',78 union all
select '张三','数学',68 union all
select '张三','英语',74 union all
select '王五','语文',56 union all
select '王五','数学',89 union all
select '王五','英语',88 union all
select '李四','语文',75 union all
select '李四','数学',64 union all
select '李四','英语',76

--【查询】 
--1.全表查询数据
select * from student
--2.提取横查询 竖表 打横 case when
		姓名     语文  数学  英语
         李四	78	   68   74
         
  ----这样将是 只要不是(语文)的这一行 就设置为 0   注意 这里没有提取最大值 那么依然还是没有改变 表的结构 那么 其他的值已经设为 0了
 select  (case subject when '语文' then result else 0 end)语文,  
		(case subject when '数学' then result else 0 end)数学,
		(case subject when '英语' then result else 0 end)英语
from student 
         
         
 ---不进行分组 就会只能 有一条数据
select  MAX(case subject when '语文' then result else 0 end)语文,
				   MAX(case subject when '数学' then result else 0 end)数学,
				   max(case subject when '英语' then result else 0 end)英语
from student  
  ---以姓名为 分组依据 将【所有】的学生姓名数据都查询出来       
 select name 姓名, MAX(case subject when '语文' then result else 0 end)语文,
				   MAX(case subject when '数学' then result else 0 end)数学,
				   max(case subject when '英语' then result else 0 end)英语
from student group by name

--简单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') 
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值