postgresql 条件表达式

news/2024/7/9 20:30:10 标签: postgresql, 数据库

postgresql 条件表达式

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

简单CASE表达式

语法如下

case 表达式
	when1 then 结果1
	when2 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;

在这里插入图片描述

总结

在这里插入图片描述


http://www.niftyadmin.cn/n/4963211.html

相关文章

【25考研】- 整体规划及高数一起步

【25考研】- 整体规划及高数一起步 一、整体规划二、专业课870计算机应用基础参考网上考研学长学姐&#xff1a; 三、高数一典型题目、易错点及常用结论&#xff08;一&#xff09;典型题目&#xff08;二&#xff09;易错点&#xff08;三&#xff09;常用结论1.arcsinxarccos…

IDEA常用插件之依赖关系查看Maven Helper

文章目录 安装使用 安装 使用 安装完成后点击pom.xml文件&#xff0c;可以查看Maven依赖关系

VS2022Toolbox怎么打开(VS2022工具箱在哪)

文章目录 显示ToolboxToolbox的位置 显示Toolbox 单击菜单栏的“视图”> “工具箱”。 Toolbox的位置 如图&#xff0c;最左侧。

Linux 内核编译参数

文章目录 前言1 -Wall2 -Wundef3 -Wstrict-prototypes4 -Wno-trigraphs5 -fno-strict-aliasing6 -fno-common7 -Werror-implicit-function-declaration8 -Wno-format-security9 -fno-delete-null-pointer-checks10 -stdgnu89 前言 # cat /etc/os-release NAME"CentOS Lin…

VMware Workstation Pro 无法使用开机状态下拍的快照来克隆虚拟机,怎么解决?

环境: VMware Workstation Pro16.0 Win10 专业版 问题描述: VMware Workstation Pro有台虚拟机在开机状态下拍了个6.7快照这个win10初始版,现在想在这个快照下直接克隆,无法使用开机状态下拍的快照创建克隆 解决方案: 1.关闭当前虚拟机 2.到虚拟机文件夹复制一份Wind…

对比flink cdc和canal获取mysql binlog优缺点

Flink CDC和Canal都是用于获取MySQL binlog的工具&#xff0c;但是有以下几点优缺点对比&#xff1a; Flink CDC是一个基于Flink的库&#xff0c;可以直接在Flink中使用&#xff0c;无需额外的组件或服务&#xff0c;而Canal是一个独立的服务&#xff0c;需要单独部署和运行&a…

高数保研复习

可导一定连续&#xff0c;但是连续不一定可导。 一元函数可导和可微等价。 f ′ ( x 0 ) lim ⁡ Δ x → 0 Δ y Δ x lim ⁡ Δ x → 0 f ( x 0 Δ x ) − f ( x 0 ) Δ x f^{\prime}\left(x_{0}\right)\lim _{\Delta x \rightarrow 0} \frac{\Delta y}{\Delta x}\lim _{\…

C++11的四种强制类型转换

目录 语法格式 static_cast(静态转换) dynamic_cast(动态转换) const_cast&#xff08;常量转换&#xff09; reinterpret_cast(重解释) 语法格式 cast-name <typename> (expression) 其中cast-name为static_cast、dynamic_cast、const_cast 和 reinterpret_cast之一…