如何在postgresql中计算空值?

问题描述 投票:0回答:6
select distinct "column" from table;

输出:

    column
1     0.0
2     [null]
3     1.0

但是当我尝试计算空值时

select count("column") from train where "column" is NULL;

给出输出 0(零)

你能指出哪里出了问题吗?

sql postgresql count null
6个回答
21
投票

使用

count(*)

select count(*) from train where "column" is NULL;

count()
与任何其他参数一起计算非 NULL 值,因此如果
"column"
NULL
,则不存在。


18
投票

使用SUM

SELECT SUM(CASE WHEN column IS NULL THEN 1 ELSE 0 END) AS column_null_tally
FROM table;

8
投票

当您想要计算聚合上的值(包括 NULL 值)但不能使用

count(*)
(如果其他列也不同)时,可以使用一些解决方法。

在这些情况下,您可以使用此请求:

count(distinct("column")) + (CASE bool_or("column" is null) WHEN true THEN 1 ELSE 0 END)

其中

count(distinct(column))
会统计非空值,另一部分如果有空值则添加
1


5
投票

使用

FILTER

SELECT
  COUNT(*) FILTER (WHERE "column" IS NULL) AS is_null,
  COUNT(*) FILTER (WHERE "column" < 1.0) AS lt_one,
  COUNT(*) FILTER (WHERE "column" > 1.0) AS gt_one,
  COUNT(*) FILTER (WHERE "column" = 1.0) AS just_perfect
FROM "table";

0
投票

您得到零是因为您正在计算 null(空)值,您需要计算非空字段(例如 id 字段)中的值。

select count("id_column") from train where "data_column" is NULL;

0
投票

自从

  • select count(coalesce(t."column", 0)) from table t
    是完整的行数,有或没有 NULL:s 和
  • select count(t."column") from table t
    是没有 NULL:s 的行数,

这也有效:

Select count(coalesce(t."column", 0)) - count(t."column") FROM table t;

(这个答案也可能会帮助那些来这里计算NULL和非NULL的人,至少我在寻找它时被困在这里).

© www.soinside.com 2019 - 2024. All rights reserved.