postgresql-条件表达式

简单Case表达式

select 
e.first_name ,
e.last_name ,
e.department_id ,
case e.department_id 
 when 90 then '管理'
 when 60 then '开发'
 else '其他'
 end as "部门"
from cps.public.employees e ;
-- 统计部门员工数量
select 
-- 部门id为10,返回1
count(case e.department_id when 10 then 1 end) dept10_count,
-- 部门id为20,返回1
count(case e.department_id when 20 then 1 end) dept20_count,
-- 部门id为30,返回1
count(case e.department_id when 30 then 1 end) dept30_count
from cps.public.employees e ;

在这里插入图片描述

-- 统计部门员工数量
select 
-- 统计部门id为10的员工数量
count(*) filter(where e.department_id = 10) dept10_count,
-- 统计部门id为20的员工数量
count(*) filter(where e.department_id = 20) dept20_count,
-- 统计部门id为30的员工数量
count(*) filter(where e.department_id = 30) dept30_count
from cps.public.employees e ;

在这里插入图片描述

搜索Case表达式

select
	e.first_name ,
	e.last_name ,
	case
		when e.salary <5000 then '低收入'
		when e.salary between 5000 and 10000 then '中等收入'
		else '高收入'
	end as salarySummary
from
	cps.public.employees e;

在这里插入图片描述

缩写函数

/*
 * NULLIF 函数包含 2 个参数,如果第一个参数等于第二个参数,返回 NULL;否则,返回第一个参数的值
*/
-- 除数为0返回1
select 1/nullif(1,0) as result; 

在这里插入图片描述

/*
 * COALESCE 函数接受多个参数,返回第一个null的参数值,挨个判断,如果所有的参数都为null,就返回null
 * */
select coalesce(null,1,2) as finalResult;

在这里插入图片描述

select 
e.first_name ,
-- 奖金为空,就返回0
coalesce(e.commission_pct,0) as jintie
from cps.public.employees e ;

在这里插入图片描述

总结

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值