PgSQL必备技能之case when使用详解

case when功能

在SQL中case when的使用场景比较多,主要包括:

1、字段值转换

数据库中保存的字段值是英文,需要转换为中文再展示

2、业务逻辑判断

根据业务判断逻辑推导结论,例如根据身高、性别、体重等字段数据,判断是否肥胖

3、NULL值等特定值处理

为了方便数据分析等,对字段的特殊值进行处理,例如把null值修改为0等。

case when语法结构

case when有两种语法结构

简单语法结构

 case 字段名  when 条件值1 then 对应值1
              when 条件值2 then 对应值2
                         ......
              else 默认值 end

简单举例如下:

case fruit when 'apple' then '苹果'
                when 'orange' then '橙子'
                when 'banana' then '香蕉'
                else '其它' end

通用语法结构

case when 条件值1 then 对应值1
   when 条件值2 then 对应值2
         .......
   else 默认值 end

简单举例如下:

case when gmv > 100 then '优秀'
         when gmv > 80 then '良好'
         when gmv > 60 then '及格'
         else '不及格' end

case when 使用说明

1、当有一个when条件符合要求时,就会返回对应的then值,后面的when条件不再执行;

2、如果有多个when条件,前面的when条件范围的反面,会隐含地作为后面when条件的一个条件子项;

3、如果所有的when条件都不符合要求,就会返回最后的else值。

case when 进阶用法

1、case when嵌套

case when category = 'fruit' then case when name = 'apple' then '苹果'
                                                               when name = 'orange' then '橙子'
                                                               when name = 'banana' then '香蕉'
                                                               else '其它水果' end
        else '非水果' end

2、order by个性化排序

SELECT
CountryCode,
count(*)
FROM city
GROUP BY CountryCode
ORDER BY case when CountryCode = 'AGO' then 1 
                          when CountryCode = 'ARG' then 2 
                          else 99 end

#PostgreSQL##PgSQL#

举报
评论 0