Oracle: How to count null and non-null rows

后端 未结 6 2038
猫巷女王i
猫巷女王i 2021-02-04 01:38

I have a table with two columns that might be null (as well as some other columns). I would like to count how many rows that have column a, b, both and neither colu

相关标签:
6条回答
  • 2021-02-04 01:55

    It can be accomplished in Oracle just in 1 row:

    SELECT COUNT(NVL(potential_null_column, 0)) FROM table;
    

    Function NVL checks if first argument is null and treats it as value from second argument.

    0 讨论(0)
  • 2021-02-04 01:57

    One way to do it would be:

    select count(*) from table group by nvl2(a, 0, 1), nvl2(b, 0, 1) having nvl2(a,0,1) = nvl2(b,0,1);
    
    0 讨论(0)
  • 2021-02-04 01:59

    COUNT(expr) will count the number of rows where expr is not null, thus you can count the number of nulls with expressions like these:

    SELECT count(a) nb_a_not_null,
           count(b) nb_b_not_null,
           count(*) - count(a) nb_a_null,
           count(*) - count(b) nb_b_null,
           count(case when a is not null and b is not null then 1 end)nb_a_b_not_null
           count(case when a is null and b is null then 1 end) nb_a_and_b_null
      FROM my_table
    
    0 讨论(0)
  • 2021-02-04 02:00

    Something like this:

    SELECT sum(case 
                   when a is null and b is null then 1
                   else 0
               end) as both_null_count,
           sum(case
                   when a is null and b is not null then 1
                   else 0
               end) as only_a_is_null_count
    FROM your_table
    

    You can extend that for other combinations of null/not null

    0 讨论(0)
  • 2021-02-04 02:08
    select sum(decode(a,null,0,1)) as "NotNullCount", sum(decode(a,null,1,0)) as "NullCount"
    from myTable;
    

    Repeat for as many fields as you like.

    0 讨论(0)
  • 2021-02-04 02:12

    This worked well for me for counting getting the total count for blank cells on a group of columns in a table in oracle: I added the trim to count empty spaces as null

    SELECT (sum(case 
               when trim(a) is null Then 1
               else 0
           end)) +
       (sum(case
               when trim(b) is null 
               else 0
           end)) +
       (sum(case
               when trim(c) is null 
               else 0
           end)) as NullCount
    FROM your_table
    

    Hope this helps

    Cheers.

    0 讨论(0)
提交回复
热议问题