case语句返回null postgresql时处理空值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了case语句返回null postgresql时处理空值相关的知识,希望对你有一定的参考价值。
我有一个名为check_n的表,我有城市和价值
我写了一个查询,里面有CASE语句。以下是我的查询
select city,
CASE when (value/10)::integer = 2
then 2 END as a,
CASE when (value/10)::integer = 5
then 5 END as b,
CASE when (value/10)::integer = 3
then 3 END as c
from check_n;
我想要输出如下:
city, a, b, c
glb, 2, 5, 3
任何帮助表示赞赏。我正在使用Postgresql 9.5
另外如果我有另一个表chck_n如何使用该函数:
city | fact | value
------+--------+-------
glb | male | 22000
glb | female | 23000
glb | total | 45000
我想使用这个查询:
SELECT city,
CASE WHEN fact = 'male'
THEN value
END as males,
CASE WHEN fact= 'female'
THEN value
END as females,
CASE WHEN fact ='total'
THEN value
END as total
FROM chck_n;
答案
如果你想要每个城市一个结果,你可以这样做:
SELECT city,
CASE WHEN 2 =ANY (array_agg((value/10)::integer))
THEN 2
END as a,
CASE WHEN 5 =ANY (array_agg((value/10)::integer))
THEN 5
END as b,
CASE WHEN 3 =ANY (array_agg((value/10)::integer))
THEN 3
END as c
FROM check_n
GROUP BY city;
city | a | b | c
------+---+---+---
glb | 2 | 5 | 3
(1 row)
另一答案
我假设你的数据集:
with ds as (
select city,
CASE when (value/10)::integer = 2
then 2 END as a,
CASE when (value/10)::integer = 5
then 5 END as b,
CASE when (value/10)::integer = 3
then 3 END as c
from check_n)
select distinct city, max(a)a, max(b) b, max(c) c
from ds
group by city
以上是关于case语句返回null postgresql时处理空值的主要内容,如果未能解决你的问题,请参考以下文章
postgreSQL计算总数sum if case when
如何在 PostgreSQL、PL/pgSQL 上执行匿名代码块切换 CASE 语句?