Count NULL Values from multiple columns with SQL

后端 未结 5 1055
天命终不由人
天命终不由人 2020-12-15 20:44

I have 3 columns let say A, B, and C. I need to count the NULL values in each column.

For example:



        
相关标签:
5条回答
  • 2020-12-15 20:52
    select
        sum(case when a is null then 1 else 0 end) as a_null_count,
        sum(case when b is null then 1 else 0 end) as b_null_count,
        sum(case when c is null then 1 else 0 end) as c_null_count
    from table
    
    0 讨论(0)
  • 2020-12-15 20:53
    SELECT COUNT(*)-COUNT(A) As A, COUNT(*)-COUNT(B) As B, COUNT(*)-COUNT(C) As C
    FROM YourTable; 
    
    0 讨论(0)
  • 2020-12-15 20:56
    SELECT
    (SELECT count(*) FROM my_table WHERE A is NULL) as A,
    (SELECT count(*) FROM my_table WHERE B is NULL) as B,
    (SELECT count(*) FROM my_table WHERE C is NULL) as C
    
    0 讨论(0)
  • 2020-12-15 20:58

    You can use an aggregate function with a CASE expression:

    select 
      sum(case when a is null then 1 else 0 end) A,
      sum(case when b is null then 1 else 0 end) B,
      sum(case when c is null then 1 else 0 end) C
    from yt
    

    See Demo

    0 讨论(0)
  • 2020-12-15 21:19

    For SQL SERVER you can use the following:

    SET NOCOUNT ON
    DECLARE @Schema NVARCHAR(100) = '<Your Schema>'
    DECLARE @Table NVARCHAR(100) = '<Your Table>'
    DECLARE @sql NVARCHAR(MAX) =''
    IF OBJECT_ID ('tempdb..#Nulls') IS NOT NULL DROP TABLE #Nulls
    
    CREATE TABLE #Nulls (TableName sysname, ColumnName sysname , ColumnPosition int ,NullCount int , NonNullCount int)
    
     SELECT @sql += 'SELECT  '''+TABLE_NAME+''' AS TableName , '''+COLUMN_NAME+''' AS ColumnName,  '''+CONVERT(VARCHAR(5),ORDINAL_POSITION)+''' AS ColumnPosition, SUM(CASE WHEN '+COLUMN_NAME+' IS NULL THEN 1 ELSE 0 END) CountNulls , COUNT(' +COLUMN_NAME+') CountnonNulls FROM '+QUOTENAME(TABLE_SCHEMA)+'.'+QUOTENAME(TABLE_NAME)+';'+ CHAR(10)
     FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = @Schema
     AND TABLE_NAME = @Table
    
     INSERT INTO #Nulls 
     EXEC sp_executesql @sql
    
     SELECT * 
     FROM #Nulls
    
     DROP TABLE #Nulls
    

    you will receive a result set with the count of Null values and non null values in each column of you table

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