Sql-Server

計算任何 3 列具有值的位置(不為空)

  • April 5, 2019

我有一個名為ItemProperties的表,有 15 列。列名稱如Feature1、Feature2、Color、Length、Width、Height等……它有 10K+ 行。我需要該表中的計數,其中填充了任何 3 列(非空)。我們可以通過查詢來做到這一點嗎?

在此處輸入圖像描述

在所示範例中,查詢應返回計數為 4 行。

您可以將任何標記NULL為 0 和not NULL1 併計算總和,它將為您NULL提供連續非值的數量。

如果您只想計算恰好有 3 個not NULL值的行,請使用此程式碼(您應該為所有 15 列編寫案例總和,在我的範例中它們只有 6 個):

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;

相反,如果您想計算至少有 3 個 not NULL值的行,請將條件更改為 whereNum_of_not_NULL_columns >= 3;

引用自:https://dba.stackexchange.com/questions/192610