2016-07-01 162 views
0

我有一個簡單SELECT請求返回0 1而不是數據值

SELECT firstname, lastname, age, country 
FROM mytable 
ORDER BY id 

返回somethink像

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

欲返回1(或真)時的字段不爲空,並且0 (或false)當該字段爲空時。

在我爲例,請求應該返回

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

感謝您的幫助

+1

'情況下的firstName則0,否則,1月底;' – xQbert

+0

@xQbert看起來像一個答案,我 –

+0

如果它是什麼一個空白值'',或空白''只會是真的或假的? WHEN ... IS NULL THEN 0 ELSE 1會返回''會有一個值。你很多人想要測試字符串數據類型的長度LEN(),並在字的開始和結尾處修剪空格。當LEN(ISNULL(LTRIM(RTRIM(field)),''))> 0 THEN 1 ELSE 0 ..... – Matt

回答

1

您可以選擇布爾表達式直接拿truefalse爲你的結果。

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

它的工作原理,但它的巨大音量非常緩慢 – Macbernie

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 
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