当前位置: 首页 > news >正文

postgresql 条件表达式

postgresql 条件表达式

  • 简单CASE表达式
  • 搜索CASE表达式
  • 缩写函数
    • nullif函数
      • 示例
    • coalesce函数
  • 总结

简单CASE表达式

语法如下

case 表达式when1 then 结果1when2 then 结果2else 默认值
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 结果1when 条件2 then 结果2else 默认结果
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 表达式表示为:

CASEWHEN expression_1 = expression_2 THEN NULLELSE 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 表达式表示为:

casewhen 表达式1 is not null then 表达式1when 表达式2 is not null then 表达式2when 表达式3 is not null then 表达式3
end
-- 查询佣金比率为空的数据显示为 0
select 
e.first_name ,
coalesce(e.commission_pct,0) as commissionPct
from cps.public.employees e;

在这里插入图片描述

总结

在这里插入图片描述

http://www.lryc.cn/news/142600.html

相关文章:

  • 姜启源数学模型第五版第五章火箭发射升空
  • 局域网中电脑共享文件给手机
  • 线段树练习
  • Mybatis映射.动态sql.分页
  • springboot向resources下写文件的两种方式
  • Sloare flare网卡信息
  • Redis知识点整理
  • React笔记(一)初识React
  • C语言——指针进阶(一)
  • 【ArcGIS Pro二次开发】(62):复制字段
  • 【Tkinter系列02/5】界面初步和布局
  • 2023年03月 C/C++(四级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • 介绍一些编程语言— CSS 语言
  • 一文讲清楚c/c++中的宏
  • typescript进阶语法
  • 宝塔终端 查看 7003端口 占用 并且杀死
  • 可解释性的相关介绍
  • AUTOSAR规范与ECU软件开发(实践篇)6.7 服务软件组件与应用层软件组件端口连接
  • 菜鸟教程《Python 3 教程》笔记(6):列表
  • LeetCode-56-合并区间
  • Git gui教程---番外篇 gitignore 的文件使用
  • javaee spring 用注解的方式实现ioc
  • Linux基础(二)
  • 155. 最小栈(中等系列)
  • 用python从零开始做一个最简单的小说爬虫带GUI界面(3/3)
  • SpringBoot+Vue如何写一个HelloWorld
  • 深度强化学习。介绍。深度 Q 网络 (DQN) 算法
  • 【C++随笔02】左值和右值
  • 几个nlp的小任务(多选问答)
  • 【C++学习记录】为什么需要异常处理,以及Try Catch的使用方法