sql 语句中的case when

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

两种方式可以实现相同的功能。但稍微有点区别。具体在工作中使用最方便快捷的方式解决问题,事后可以深入研究。

1.简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。
2.还有一个需要注重的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。

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

一般的case when语句的使用方法网上都有,但是相对于多条件的判断就比较少,一般使用case 搜索函数


SXDIH{Q5TLIH~CQDI`4OJHC.png
SQL> select  u.id  u.nane   namer= (
case when (u.name='张五' and u.sex='2')  then '大哥')  
when  (u.name='张六' and u.sex='1')  then '二哥')
when  (u.name='张七' and u.sex='2')  then '三哥'))  from user u
                      

你可能感兴趣的:(sql 语句中的case when)