相关疑难解决方法(0)

SELECT max(x)返回null; 怎么能让它返回0?

运行以下命令时,如何返回0而不是null:

SELECT MAX(X) AS MaxX
FROM tbl
WHERE XID = 1
Run Code Online (Sandbox Code Playgroud)

(假设没有XID = 1的行)

sql sql-server

62
推荐指数
5
解决办法
10万
查看次数

将字符串转换为数字,将null或空字符串解释为0

我有一个Postgres表,其中包含一个带有数值的字符串列.我需要将这些字符串转换为数字的数字,但我需要将两个NULL值以及空字符串解释为0.

我可以将空字符串转换为空值:

# select nullif('','');
 nullif 
--------

(1 row)
Run Code Online (Sandbox Code Playgroud)

我可以将null值转换为0:

# select coalesce(NULL,0);
 coalesce 
----------
        0
(1 row)
Run Code Online (Sandbox Code Playgroud)

我可以将字符串转换为数字:

# select cast('3' as float);
 float8 
--------
      3
(1 row)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试结合这些技术时,我会遇到错误:

# select cast( nullif( coalesce('',0), '') as float);
ERROR:  invalid input syntax for integer: ""
LINE 1: select cast( nullif( coalesce('',0), '') as float);

# select coalesce(nullif('3',''),4) as hi;
ERROR:  COALESCE types text and integer cannot be matched
LINE …
Run Code Online (Sandbox Code Playgroud)

sql postgresql syntax

32
推荐指数
3
解决办法
7万
查看次数

标签 统计

sql ×2

postgresql ×1

sql-server ×1

syntax ×1