SQL如何将Null不参与计算
将得分为Null的值不参与计算
--creaFuntion
create Table #Value --得分表
(
[ID] int,
[A] int,
[B] int,
[C] int,
)
create Table #Wei
(
[ID] int,
[A1] int,
[B1] int,
[C1] int
)
insert into #Value(ID,A,B,C) values(1,90,80,100);
insert into #Value(ID,A,B,C) values(2,100,100,100);
insert into #Value(ID,A,B,C) values(3,null,NULL,NULL);
insert into #Value(ID,A,B,C) values(4,100,100,100);
insert into #Wei(ID,A1,B1,C1) values(1,2,100,1);
insert into #Wei(ID,A1,B1,C1) values(2,1,1,1);
insert into #Wei(ID,A1,B1,C1) values(3,1,1,1);
insert into #Wei(ID,A1,B1,C1) values(4,1,1,1);
--根据公式 ID1的计算平均值是: A*A1+B*B1+C*C1/(A1+B1+C1)
-- case when A is null then 0 else IsNull(A1,0) end 可以做成一个函数
select #Wei.ID as ID, A*A1 as A2 , B*B1 as B2 ,C*C1 as C2,
case when A is null then 0 else IsNull(A1,0) end
+case when B is null then 0 else IsNull(B1,0) end
+case when C is null then 0 else IsNull(C1,0) end as Wei Into #temp
from #Value,#Wei where #Value.ID = #Wei.ID
select * from #temp;
--判断权重和是否为0
select ID , case when Wei = 0 then Null
else (IsNull(A2,0)+IsNull(B2,0)+IsNull(C2,0))/Wei
end as Score
from #temp;
drop table #value;
drop table #Wei;
drop table #temp;
结果
ID A2 B2 C2 Wei
1 90 80 100 3
2 100 null 100 2
3 null null null 0
4 100 100 100 3
ID Score
1 90
2 100
3 Null
4 100