简体   繁体   English

如何计算postgresql中的空值?

[英]How to count null values in postgresql?

select distinct "column" from table;

output:输出:

    column
1     0.0
2     [null]
3     1.0

But when I try to count the null values但是当我尝试计算空值时

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

Gives output 0 (zero)给出输出 0(零)

Can you suggest where it's going wrong?你能建议哪里出了问题吗?

Use count(*) :使用count(*)

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

count() with any other argument counts the non-NULL values, so there are none if "column" is NULL . count()与任何其他参数计算非 NULL 值,因此如果"column"NULL则没有。

Some workaround when you want to count the values on aggregations, including NULL ones, but can't use count(*) (if other columns are different too).当您想要计算聚合值(包括 NULL 值)但不能使用count(*) (如果其他列也不同)时的一些解决方法。

On these cases, you can use this request :在这些情况下,您可以使用此请求:

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

The count(distinct(column)) will count the non null values, and the other part will add 1 if there is a null value count(distinct(column))会统计非空值,如果有空值,另一部分加1

Use SUM使用总和

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

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

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

Use FILTER<\/code><\/a>使用FILTER<\/code><\/a>

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

Since自从

  • select count(coalesce(t."column", 0)) from table t is the full number with NULL:s and select count(coalesce(t."column", 0)) from table t is the full number with NULL:s 和
  • select count(t."column") from table t is the number without NULL:s, select count(t."column") from table t是没有 NULL:s 的数字,

this works as well:这也有效:

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

(This answer might also help those who came here to count both NULL and not NULL, at least I was stranded here since I was searching for that) . (这个答案也可能帮助那些来到这里的人同时计算 NULL 和 not NULL,至少我在寻找它时被困在这里)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM