Counting null and non-null values in a single query

后端 未结 26 1053
星月不相逢
星月不相逢 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 19:51

    Number of elements where a is null:

    select count(a) from us where a is null;
    

    Number of elements where a is not null:

    select count(a) from us where a is not null;
    
    0 讨论(0)
  • 2021-01-29 19:53

    Just to provide yet another alternative, Postgres 9.4+ allows applying a FILTER to aggregates:

    SELECT
      COUNT(*) FILTER (WHERE a IS NULL) count_nulls,
      COUNT(*) FILTER (WHERE a IS NOT NULL) count_not_nulls
    FROM us;
    

    SQLFiddle: http://sqlfiddle.com/#!17/80a24/5

    0 讨论(0)
  • 2021-01-29 19:54
    SELECT
        ALL_VALUES
        ,COUNT(ALL_VALUES)
    FROM(
            SELECT 
            NVL2(A,'NOT NULL','NULL') AS ALL_VALUES 
            ,NVL(A,0)
            FROM US
    )
    GROUP BY ALL_VALUES
    
    0 讨论(0)
  • 2021-01-29 19:56

    If I understood correctly you want to count all NULL and all NOT NULL in a column...

    If that is correct:

    SELECT count(*) FROM us WHERE a IS NULL 
    UNION ALL
    SELECT count(*) FROM us WHERE a IS NOT NULL
    

    Edited to have the full query, after reading the comments :]


    SELECT COUNT(*), 'null_tally' AS narrative 
      FROM us 
     WHERE a IS NULL 
    UNION
    SELECT COUNT(*), 'not_null_tally' AS narrative 
      FROM us 
     WHERE a IS NOT NULL;
    
    0 讨论(0)
  • 2021-01-29 19:56

    if its mysql, you can try something like this.

    select 
       (select count(*) from TABLENAME WHERE a = 'null') as total_null, 
       (select count(*) from TABLENAME WHERE a != 'null') as total_not_null
    FROM TABLENAME
    
    0 讨论(0)
  • 2021-01-29 19:57
    SELECT SUM(NULLs) AS 'NULLS', SUM(NOTNULLs) AS 'NOTNULLs' FROM 
        (select count(*) AS 'NULLs', 0 as 'NOTNULLs' FROM us WHERE a is null
        UNION select 0 as 'NULLs', count(*) AS 'NOTNULLs' FROM us WHERE a is not null) AS x
    

    It's fugly, but it will return a single record with 2 cols indicating the count of nulls vs non nulls.

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