简单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 ;
总结
本文含有隐藏内容,请 开通VIP 后查看