[英]How to count null values in postgresql?
select distinct "column" from table;
輸出:
column
1 0.0
2 [null]
3 1.0
但是當我嘗試計算空值時
select count("column") from train where "column" is NULL;
給出輸出 0(零)
你能建議哪里出了問題嗎?
使用count(*)
:
select count(*) from train where "column" is NULL;
count()
與任何其他參數計算非 NULL 值,因此如果"column"
為NULL
則沒有。
當您想要計算聚合值(包括 NULL 值)但不能使用count(*)
(如果其他列也不同)時的一些解決方法。
在這些情況下,您可以使用此請求:
count(distinct("column")) + (CASE bool_or("column" is null) WHEN true THEN 1 ELSE 0 END)
count(distinct(column))
會統計非空值,如果有空值,另一部分加1
使用總和
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;
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";
自從
select count(coalesce(t."column", 0)) from table t
is the full number with NULL:s 和select count(t."column") from table t
是沒有 NULL:s 的數字,這也有效:
Select count(coalesce(t."column", 0)) - count(t."column") FROM table t;
(這個答案也可能幫助那些來到這里的人同時計算 NULL 和 not NULL,至少我在尋找它時被困在這里) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.