计算一行表中的空列数

时间:2012-09-20 13:13:04

标签: sql sql-server sql-server-2008 null

  

可能重复:
  How to count in SQL all fields with null values in one record?

我有五列的表格:

Name     DOB    Email      phone   jobtitle
abc     null   a@c.com      null       null
bbc     null    null        null       null

如何编写查询以便我可以找到一行中的空列数?

(例如,第1行具有3个空值,第2行具有4个空值。)

我正在使用SQL Server 2008.

2 个答案:

答案 0 :(得分:1)

天真的方式:

SELECT CASE WHEN Name IS NULL THEN 1 ELSE 0 END +
    CASE WHEN DOB IS NULL THEN 1 ELSE 0 END +       
    CASE WHEN Email IS NULL THEN 1 ELSE 0 END +       
    CASE WHEN phone IS NULL THEN 1 ELSE 0 END +       
    CASE WHEN jobtitle IS NULL THEN 1 ELSE 0 END

但我不想写其中的76个。那么动态方式如何(未经测试,但沿着这些方向):

DECLARE @SQL NVARCHAR(4000);    
SET @SQL = 'SELECT theTable.ID, ' + 
    STUFF((SELECT '+ CASE WHEN ' + QUOTENAME(COLUMN_NAME) + 
        ' IS NULL THEN 1 ELSE 0 END' 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_NAME = 'theTable' FOR XML PATH('')) , 1 , 1 , '') 
    + ' FROM theTable';    
EXEC(@SQL);

答案 1 :(得分:-2)

我认为唯一的方法是指定每个列

select sum(case when item1 is null then 1 else 0 end
          +case when item2 is null then 1 else 0 end
          +case when item3 is null then 1 else 0 end
          +case when item4 is null then 1 else 0 end
          +case when item5 is null then 1 else 0 end
          +case when item6 is null then 1 else 0 end
          ) as grandtotalnulls
  from yourtable