You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hive SQL中多次调用rand函数导致数据分布不符合预期的原因

Hive SQL随机分布不符合预期的原因

执行的SQL语句

drop table if exists temp_a;
create table temp_a
as
select 
 case when rand(123) < 0.4 then 1 
      when  rand(123) >= 0.4 and rand(123) < 0.8 then 2 
      else 3 end as label 
from source_data ;

select label, count(1) as count from temp_a group by label;

执行结果

label   count(1)    
1       111175     
2       80509       
3       87690      

计算后的分布

distribution 
label  count / sum
1      40%
2      28%
3      32%

原因分析

问题核心是CASE表达式中多次调用rand(123)函数:

  • 每次调用rand(123)都会重新生成随机数,而非复用同一个值。比如第一个条件判断用了一个随机数,若不满足进入第二个条件时,会再次生成新的随机数进行判断,完全打乱了原本的区间划分逻辑。
  • 预期逻辑是用同一个随机数划分:<0.4为1、0.4~0.8为2、>=0.8为3,但多次调用rand函数后,同一行在不同条件判断时使用不同随机数,最终导致分布偏离预期。

修正方案

先将rand(123)的结果赋值给临时变量,再用该变量做CASE判断,确保每行只用同一个随机数:

drop table if exists temp_a;
create table temp_a
as
select 
  case when rand_num < 0.4 then 1 
       when rand_num >= 0.4 and rand_num < 0.8 then 2 
       else 3 end as label 
from (
    select rand(123) as rand_num from source_data
) t ;

select label, count(1) as count from temp_a group by label;

内容的提问来源于stack exchange,提问作者cai zoro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:12:44