count(else null)和count(else 0)区别
背景:工作时候写了一段代码,目的是取出创建订单和成功单,然后发现创建单和成功单数据一致,无论怎么检查,都没发现问题出在哪里(代码如下)。
select
pdate,
unionid,
count(distinct unionid) create_uv,
count(distinct case when success=1 then unionid else 0 end) over_uv
FROM table WHERE pdate>='2024-02-10' and pdate<='2024-02-16'
AND isvalid = 1
AND istest = 0
group by pdate
被逼无奈拿出明细,发现结果中竟然有success=3的订单被误判为成功单,这到底是怎么回事呢?
其实,这个因为count()语句中应该是使用null,代码更正如下:
select
pdate,
unionid,
count(distinct unionid) create_uv,
count(distinct case when success=1 then unionid else null end) over_uv
FROM table WHERE pdate>='2024-02-10' and pdate<='2024-02-16'
AND isvalid = 1
AND istest = 0
group by pdate
主要是因为count(distinct) 函数会计算指定字段中不同值的个数。
当使用 else null 时,count(distinct) 函数只会计算 case when issuccess=1 条件成立的记录数,因为 case when success=1 条件不成立的记录会被剔除掉,不会被计算在内。这样计算出来的 count(distinct) 结果会小一些。
而当使用 else 0 时,无论success 是否等于 1,unionid 都会被计算到结果中。当 success=1 不成立时,unionid 的值为 0。在 count(distinct) 函数中,0 值是一个有效的值,因此所有不同的unionid 值,包括值为 0 的,都会被计算进去。
关注公众号「水沐教育科技」,在手机上阅读所有教程,随时随地都能学习。内含一款搜索神器,免费下载全网书籍和视频。

微信扫码关注公众号