在聚合函数里边进行数据筛选

tech2025-07-30  6

背景:如图所示,比如我需要计算sum(A)/sum(B)

IDAB1111222null3333

如果我直接对聚合进行计算 (11+22+33)/(1+3) = 16.5 显然这是存在一定误差的,现在需求是将为null的数据整行不参与计算。 方案一:很简单 直接对整行进行判断并筛选:

select sum(A)/sum(B) from testsum1 where A is not null and B is not null;

方案二:在聚合函数中进行数据筛选:

select sum(case when A is not null and B is not null then A else 0 end)/ sum(case when A is not null and B is not null then B else 0 end) from testsum1;

总结:我个人更推荐方案二,很多人或许会疑惑,但是真正的应用场景中,我查询的是一个非常大的表,如果我通过where进行筛选必然会影响其他字段的求值,当然我也可以单独 left join 这个结果出来,这样会使得代码看起来非常冗余。

最新回复(0)