postgresql 条件表达式
- 简单CASE表达式
 - 搜索CASE表达式
 - 缩写函数
 - nullif函数
 - 示例
 
- coalesce函数
 
- 总结
 
简单CASE表达式
语法如下
case 表达式
	when 值1 then 结果1
	when 值2 then 结果2
	else 默认值
end;
 
select 
e.first_name ,
e.last_name ,
case e.department_id 
when 90 then '管理'
when 60 then '开发'
else '其他'
end as "部门"
from employees e ;
 

搜索CASE表达式
case 
	when 条件1 then 结果1
	when 条件2 then 结果2
	else 默认结果
end
 
根据薪水的范围将员工的收入分为高中低三个档次
select 
e.first_name ,
e.last_name,
e.salary ,
case 
	when e.salary <5000 then '低收入'
	when e.salary between 5000 and 10000 then '中等收入'
	else '高收入'
end as "收入"
from public.employees e ;
 

缩写函数
nullif函数
语法如下
nullif(表达式1,表达式2)
 
NULLIF 函数包含 2 个参数,如果第一个参数等于第二个参数,返回 NULL;否则,返回第
 一个参数的值,它可以使用等价的 CASE 表达式表示为:
CASE
 WHEN expression_1 = expression_2 THEN NULL
 ELSE expression_1
END
 
示例
select nullif(1, 1), nullif('a', 'b');
 

 nullif 还有常见的用法就是除数为0的错误
select 1 / nullif(0,0) as t;
 

coalesce函数
coalesce (表达式1,表达式2,表达式3)
 
COALESCE 函数接受多个参数,并且返回第一个非空的参数值;如果所有参数都为空值,
 返回 NULL 值。它可以使用等价的 CASE 表达式表示为:
case
 when 表达式1 is not null then 表达式1
 when 表达式2 is not null then 表达式2
 when 表达式3 is not null then 表达式3
end
 
-- 查询佣金比率为空的数据显示为 0
select 
e.first_name ,
coalesce(e.commission_pct,0) as commissionPct
from cps.public.employees e;
 

总结




















