SQL语句之if,case

其他函数 、 case 语句

  1. 聚合函数
    max() , min() , avg() , sum() , count ()

  2. if( bool表达式 , expr1 , expr2 )
    如果 bool表达式 成立 (true) , 就返回 expr1 。 否则 如果 bool表达式 不成立 (false) , 就返回 expr2 。

类似于 java 语言中的 问号表达式 ( ? : )

select sid,cid, if(mark>=60,’及格’,’不及格’) as ‘成绩’ from score

  1. ifnull ( expr1 , expr2 )
    如果 expr1 不为null 就返回 expr1 自己。 否则 如果 expr1 为null , 就返回 expr2 。

select * from score;

update score set mark=null where sid=2001002 and cid=’01’

alter table score
modify mark decimal(8,2)

select ifnull(mark,0) from score

  1. isnull ( exp )
    判断 表达式(或者列名) exp 是否为null 。 如果 为null ,就返回 1 (表示 : true) , 否则返回 0 (表示:false )

select * from score where mark is null

select * from score where isnull(mark)

  1. case 语句
    (1) 语法1 : 类似于 java 语言中的 switch

case 表达式exp
when 比较值1 then ‘选择的结果1’
when 比较值2 then ‘选择的结果2’
when 比较值3 then ‘选择的结果3’
when 比较值4 then ‘选择的结果4’
else ‘选择的结果5’
end

select

case cid
when ’01’ then ‘语文’
when ’02’ then ‘数学’
else ‘出错’
end

from score

(2) 语法2 : 类似于 java 语言中的 if

case
when bool表达式1 then ‘选择的结果1’
when bool表达式2 then ‘选择的结果2’
when bool表达式3 then ‘选择的结果3’
when bool表达式4 then ‘选择的结果4’
else ‘选择的结果5’
end

select sid,cid,
case
when mark >=80 then ‘优秀’
when mark >=60 then ‘及格’
else ‘不及格’
end as ‘level’
from score

Original: https://www.cnblogs.com/daimenglaoshi/p/16859478.html
Author: 呆萌老师
Title: SQL语句之if,case

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/714339/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球