【问题标题】:How to get count of columns that are having null values for a given row in sql?如何获取sql中给定行具有空值的列数?
【发布时间】:2020-09-15 12:26:40
【问题描述】:
我有一个有 115 列的表。
在 7 列中,我需要获取给定行的非空值的列数。
【问题讨论】:
-
-
Deepa Das - 如果this question 的答案之一解决了您的问题,您可以通过将其标记为已接受来帮助社区。接受的答案有助于未来的访问者自信地使用该解决方案。
标签:
mysql
sql
multiple-columns
notnull
【解决方案1】:
一种方法是使用case和+:
select t.*,
( (case when col1 is not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 else 0 end) +
(case when col4 is not null then 1 else 0 end) +
(case when col5 is not null then 1 else 0 end) +
(case when col6 is not null then 1 else 0 end) +
(case when col7 is not null then 1 else 0 end)
) as cnt_not_nulls_in_row
from t;
在 MySQL 中,这可以简化为:
select t.*,
( (col1 is not null ) +
(col2 is not null ) +
(col3 is not null ) +
(col4 is not null ) +
(col5 is not null ) +
(col6 is not null ) +
(col7 is not null )
) as cnt_not_nulls_in_row
from t;
【解决方案2】:
您可以先使用主键从table 中查询给定的row,然后使用COUNT 计算查询行中具有空值的列数,如下所示:
WITH derived_row as
(SELECT col1, col2, col3, col4, col5, col6, col7 FROM table WHERE primary_key=key)
SELECT COUNT(CASE
WHEN col1 IS NULL THEN 1
WHEN col2 IS NULL THEN 1
WHEN col3 IS NULL THEN 1
WHEN col4 IS NULL THEN 1
WHEN col5 IS NULL THEN 1
WHEN col6 IS NULL THEN 1
WHEN col7 IS NULL THEN 1
END) AS null_column_count
FROM derived_row;