declare @ItemProperties table (col1 int, col2 int, col3 int, col4 int, col5 int, col6 int);
insert into @ItemProperties
values
(1, 1, 1, null, null, 1),
(1, null, null, null, null, 1),
(null, 1, 1, 1, null, null),
(null, null, 1, null, null, 1),
(null, 1, 1, 1, 1, 1);
with cte as
(
select *,
case when col1 is null then 0 else 1 end +
case when col2 is null then 0 else 1 end +
case when col3 is null then 0 else 1 end +
case when col4 is null then 0 else 1 end +
case when col5 is null then 0 else 1 end +
case when col6 is null then 0 else 1 end as Num_of_not_NULL_columns
from @ItemProperties
)
--select *
--from cte
--where Num_of_not_NULL_columns = 3
select count(*) as cnt
from cte
where Num_of_not_NULL_columns = 3;
您可以将任何标记
NULL
为 0 和not NULL
1 并计算总和,它将为您NULL
提供一行中非值的数量。如果您只想计算恰好有 3 个
not NULL
值的行,请使用此代码(您应该为所有 15 列编写个案总和,在我的示例中它们只有 6 个):相反,如果您想计算具有至少 3 个
not NULL
值的行,请将条件更改为 whereNum_of_not_NULL_columns >= 3;