case语句返回null postgresql时处理空值

时间:2017-12-21 10:11:55

标签: sql postgresql null case

我有一张名为 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;

在下图enter image description here

中附加输出

我想要输出如下:

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;

2 个答案:

答案 0 :(得分:2)

如果你想要每个城市有一个结果,你可以这样做:

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)

答案 1 :(得分:2)

我假设你的数据集:

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