Counting null and non-null values in a single query

后端 未结 26 1083
星月不相逢
星月不相逢 2021-01-29 19:31

I have a table

create table us
(
 a number
);

Now I have data like:

a
1
2
3
4
null
null
null
8
9

Now I need

相关标签:
26条回答
  • 2021-01-29 20:03

    Here is a quick and dirty version that works on Oracle :

    select sum(case a when null then 1 else 0) "Null values",
           sum(case a when null then 0 else 1) "Non-null values"
    from us
    
    0 讨论(0)
  • 2021-01-29 20:03

    use ISNULL embedded function.


    0 讨论(0)
  • 2021-01-29 20:04

    usually i use this trick

    select sum(case when a is null then 0 else 1 end) as count_notnull,
           sum(case when a is null then 1 else 0 end) as count_null
    from tab
    group by a
    
    0 讨论(0)
  • 2021-01-29 20:04

    Just in case you wanted it in a single record:

    select 
      (select count(*) from tbl where colName is null) Nulls,
      (select count(*) from tbl where colName is not null) NonNulls 
    

    ;-)

    0 讨论(0)
  • 2021-01-29 20:05

    In my case I wanted the "null distribution" amongst multiple columns:

    SELECT
           (CASE WHEN a IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS a_null,
           (CASE WHEN b IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS b_null,
           (CASE WHEN c IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS c_null,
           ...
           count(*)
    FROM us
    GROUP BY 1, 2, 3,...
    ORDER BY 1, 2, 3,...
    

    As per the '...' it is easily extendable to more columns, as many as needed

    0 讨论(0)
  • 2021-01-29 20:06

    As i understood your query, You just run this script and get Total Null,Total NotNull rows,

    select count(*) - count(a) as 'Null', count(a) as 'Not Null' from us;
    
    0 讨论(0)
提交回复
热议问题