使用 SQL 计算多列中的 NULL 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16528682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:11:48  来源:igfitidea点击:

Count NULL Values from multiple columns with SQL

sql

提问by Anonymoose

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

我有3列让说ABC。我需要计算NULL每列中的值。

For example:

例如:

 A  | B  | C
-------------
1   |NULL| 1
1   | 1  | NULL
NULL| 1  | 1
NULL|NULL| 1

Should output:

应该输出:

 A  |  B  |  C
---------------
 2  |  2  |  1

I've tried count, sum, sub-queries but nothing has worked for me yet. Any input would be appreciated!

我已经尝试过计数、总和、子查询,但还没有对我有用。任何输入将不胜感激!

回答by PM 77-1

SELECT COUNT(*)-COUNT(A) As A, COUNT(*)-COUNT(B) As B, COUNT(*)-COUNT(C) As C
FROM YourTable; 

回答by Taryn

You can use an aggregate function with a CASEexpression:

您可以将聚合函数与CASE表达式一起使用:

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

演示

回答by hkravitz

For SQL SERVER you can use the following:

对于 SQL SERVER,您可以使用以下内容:

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

您将收到一个结果集,其中包含表的每一列中的 Null 值和非 Null 值的计数

回答by Daniel

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

回答by dmansfield

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

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