简体   繁体   中英

Count NULL values by column in SQL

Suppose I have the following table:

table

| a    | b   | c    |
|:-----|:----|:-----|
| 1    | a   | NULL |
| NULL | b   | NULL |
| 3    | c   | NULL |
| 4    | d   | 23   |
| NULL | e   | 231  |

How can I count the number of NULL values by each column?

My final result would be:

| column_name    | n_nulls   |
|:---------------|:----------|
| a              | 2         |
| b              | 0         |
| c              | 3         |

You can use union all :

select 'a', count(*) - count(a) as n_nulls from t
union all
select 'b', count(*) - count(b) as n_nulls from t
union all
select 'c', count(*) - count(c) as n_nulls from t;

Redshift is a column-store database, so there probably is not a more efficient method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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