postgresql - postgresql : how to do query "case when ... else nothing"

标签 postgresql

我有一列 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;

最佳答案

添加else在 case 表达式中为 else 'zero' , 所以它会返回 zero对于不匹配的 POSNEG值(value)观。

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

Is there any way to not select zero?

如果是这样,请避免在 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';

关于postgresql - postgresql : how to do query "case when ... else nothing",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807401/

相关文章:

postgresql - 在 PostgreSQL 中查找字符串并按到字符串开头的距离排序

python - 在 python 中使用 SQLAlchemy 将行迭代地插入到 postgreSQL 数据库中

postgresql - 我可以通过 libpq 将时间发送到 postgres 吗?

postgresql - 是否可以在 postgresql 的另一个模式中使用一个模式的枚举类型

sql - 在Postgresql中,对2列添加唯一约束,不等于特定值

php - 使用 PHP 将 DESCRIBE TABLE Postgres 导出到 .txt 文件

django 如何为 postgresql 数据库中现有的多对多表定义模型

postgresql - 将数百批 500k - 300 万条记录插入 PostgreSQL 数据库的最快方法

java - QueryDsl:使用 or() 和 not() 为条件生成错误的 sql

sql - 如何使用 manage.py 加载 .sql 文件