Counting null and non-null values in a single query

后端 未结 26 1077
星月不相逢
星月不相逢 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:41

    Try this..

    SELECT CASE 
             WHEN a IS NULL THEN 'Null' 
             ELSE 'Not Null' 
           END a, 
           Count(1) 
    FROM   us 
    GROUP  BY CASE 
                WHEN a IS NULL THEN 'Null' 
                ELSE 'Not Null' 
              END 
    
    0 讨论(0)
  • 2021-01-29 19:42

    This works for Oracle and SQL Server (you might be able to get it to work on another RDBMS):

    select sum(case when a is null then 1 else 0 end) count_nulls
         , count(a) count_not_nulls 
      from us;
    

    Or:

    select count(*) - count(a), count(a) from us;
    
    0 讨论(0)
  • 2021-01-29 19:44

    If you're using MS Sql Server...

    SELECT COUNT(0) AS 'Null_ColumnA_Records',
    (
        SELECT COUNT(0)
        FROM your_table
        WHERE ColumnA IS NOT NULL
    ) AS 'NOT_Null_ColumnA_Records'
    FROM your_table
    WHERE ColumnA IS NULL;
    

    I don't recomend you doing this... but here you have it (in the same table as result)

    0 讨论(0)
  • 2021-01-29 19:47

    Here are two solutions:

    Select count(columnname) as countofNotNulls, count(isnull(columnname,1))-count(columnname) AS Countofnulls from table name
    

    OR

    Select count(columnname) as countofNotNulls, count(*)-count(columnname) AS Countofnulls from table name
    
    0 讨论(0)
  • 2021-01-29 19:49

    I had a similar issue: to count all distinct values, counting null values as 1, too. A simple count doesn't work in this case, as it does not take null values into account.

    Here's a snippet that works on SQL and does not involve selection of new values. Basically, once performed the distinct, also return the row number in a new column (n) using the row_number() function, then perform a count on that column:

    SELECT COUNT(n)
    FROM (
        SELECT *, row_number() OVER (ORDER BY [MyColumn] ASC) n
        FROM (
            SELECT DISTINCT [MyColumn]
                        FROM [MyTable]
            ) items  
    ) distinctItems
    
    0 讨论(0)
  • 2021-01-29 19:50

    for non nulls

    select count(a)
    from us
    

    for nulls

    select count(*)
    from us
    
    minus 
    
    select count(a)
    from us
    

    Hence

    SELECT COUNT(A) NOT_NULLS
    FROM US
    
    UNION
    
    SELECT COUNT(*) - COUNT(A) NULLS
    FROM US
    

    ought to do the job

    Better in that the column titles come out correct.

    SELECT COUNT(A) NOT_NULL, COUNT(*) - COUNT(A) NULLS
    FROM US
    

    In some testing on my system, it costs a full table scan.

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