返回0 1而不是数据值

时间:2016-07-01 19:45:45

标签: sql postgresql

我有一个简单的SELECT请求

jean    dupont  35  france
hervé   yang        japon
laura           28  
mickael sylvain 65  suisse
...

返回一些想法

1   1   1   1
1   1   0   1
1   0   1   0
1   1   1   1
...

我希望当字段不为null时返回1(或true),当字段为null时返回0(或false)。

在我的例子中,请求应该返回

{{1}}

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

从布尔到整数的转换产生0或1

select
    (firstname is not null)::integer as firstname,
    (lastname is not null)::integer as lastname,
    (age is not null)::integer as age,
    (country is not null)::integer as country
from mytable
order by id

答案 1 :(得分:1)

您可以直接选择布尔表达式,以获得truefalse作为结果。

SELECT
  firstname IS NOT NULL,
  lastname IS NOT NULL,
  age IS NOT NULL,
  country IS NOT NULL
FROM mytable
ORDER BY id

答案 2 :(得分:1)

当您需要替换值时,请考虑使用case语句。它是所有RDBMS系统中最基本和最普遍支持的。

SELECT case firstName when is null then 0 else 1 end as col1
     , case lastname when is null then 0 else 1 end as col2 
     , case age when is null then 0 else 1 end as col3
     , case countrywhen is null then 0 else 1 end as col4
FROM mytable
ORDER BY id