小编Edw*_*own的帖子

计算每行 NULL 值

我想在不枚举列名的情况下计算表中每行存在的空值数。例如:

WITH t as (VALUES
  (NULL ,'hi',2,NULL,'null'),
  ('' ,'hi',2,3,'test'),
  (NULL ,'hi',2,3,'null')
)
SELECT countnulls(t)
FROM t;
Run Code Online (Sandbox Code Playgroud)

会导致:

numnulls
2
0
1
Run Code Online (Sandbox Code Playgroud)

我能得到的最接近的是以下黑客row_to_json()

select 
(CHAR_LENGTH(row_to_json(t)::text)
 - CHAR_LENGTH(REPLACE(row_to_json(t)::text, 'null', '')))/4 from t;
Run Code Online (Sandbox Code Playgroud)

这是......相当的黑客(不是很好)。它可以工作,有点,但是当它出现在实际数据或列名中时,它会将字符串 'null' 计为 NULL。所以在上述情况下是不正确的。

postgresql null isnull postgresql-9.6

5
推荐指数
1
解决办法
4531
查看次数

标签 统计

isnull ×1

null ×1

postgresql ×1

postgresql-9.6 ×1