计算表中每列的空值或非空值

时间:2018-07-30 07:56:34

标签: sql sql-server count null

我需要有关表中所有表的null / non null值的编码计数器的帮助。我知道如何在一列中执行此操作,但不知道如何将其与所有列合并。

在示例中

              CITY         STATE       CONTINENT
MICHAEL.E     NULL         NY          NA
JOHN.D        PARIS        FR          EU
NICOLAS.B     FRANKFURT    GE          EU
MING.Y        NULL         NULL        AF

所以我会得到类似

的结果
column      null       not_null ....
city        2          2
state       1          3
continent   0          4

我确信它必须与可以从

获取的所有列ID的列表一起使用
SELECT DISTINCT AC.object_id, AC.name, AC.column_id 
     FROM SYS.all_columns AC JOIN sys.all_objects AO 
       ON AC.object_id=AO.object_id 
      WHERE AO.name='MY_TABLE_NAME'

由于我有很多要处理的表,其中许多有600多个列  我需要该应用程序的解决方案。

2 个答案:

答案 0 :(得分:1)

我会使用APPLY

select cols as [column], 
       sum(case when col is null then 1 else 0 end) as [null],
       sum(case when col is not null then 1 else 0 end) as [not_null]
from table t cross apply
     ( values ('city', city), 
              ('state', state), 
              ('continent', continent),
              . . .
     ) tt (cols, col)
group by cols;

编辑

select cols, 
       sum(case when col is null then 1 else 0 end) as Null_value, 
       sum(case when col is not null then 1 else 0 end) as not_null_value 
from TABLE_NAME cross apply 
     ( values ('Column_1', Column_1), 
              ('Column_2', Column_2), 
              ('Column_3', Column_3), 
              ('Column_4', Column_4), 
              ('Column_5', Column_5)   
     ) tt (cols,col) 
group by cols;

答案 1 :(得分:0)

SQL Server和Oracle

with CTE as
(
  select ColName, ColVal
  from 
  (
    select name, city, state, continent
    from mytable
  ) t1
    unpivot
  (
    ColVal for ColName in (city, state, continent)
  )
)
select ColName,
       sum(case when ColVal is null then 1 else 0 end) as nulls,
       sum(case when ColVal is null then 0 else 1 end) as not_nulls
from CTE