首页 > 解决方案 > postgreql:如何查询“case when ... else nothing”

问题描述

我有一列category,可能有 3 个值“pos”、“neg”和“zero”。

我正在寻找一个查询,当它是 pos 时显示 POSITIVE,当它是 neg 时显示 NEGATIVE 而当它为零时什么都没有。

通过下面的查询,当它为零时我得到 null。有没有办法不选择零?

SELECT distinct(category),
case when nature='POS' then 'POSITIVE'
     when nature='NEG' then 'NEGATIVE'
end as category_rm
FROM table_h;

标签: postgresql

解决方案


将 case 表达式添加elseelse 'zero',因此它将返回zero不匹配的值POSNEG值。

SELECT distinct category,
       case when nature = 'POS' then 'POSITIVE'
            when nature = 'NEG' then 'NEGATIVE'
            else 'zero'  
       end as category_rm
FROM table_h;

有没有办法不选择零?

WHERE如果是这样,请在子句中避免它

SELECT distinct category,
       case when nature = 'POS' then 'POSITIVE'
            when nature = 'NEG' then 'NEGATIVE'
       end as category_rm
FROM table_h
WHERE nature != 'zero';

推荐阅读