编程技术安全技术算法技术

odps中的抽样与去重V0.1

2018-02-04  本文已影响7人  小谷先生

分组抽样

希望按照性别年龄分组, 去抽样查看他们的身高体重, 那么mysql可以这么写:

select height, weight from student_table group by gender, age

可odps 不支持这样的语法, 于是找到了cluster_sample() 这个函数.

 select height, weight
    from (
        select height, weight, cluster_sample(1) over(partition by  gender, age) as flag
        from student_table 
        ) sub
    where flag = true;

同样sql执行多次结果不一, 印证了在抽样时内部会有不同的随机数种子. 该函数可以满足需求.

应用: id去重

有些表, id列没有被定义为主键, 所以会有些重复, 有些脏数据, 那么怎么得到一个新的表, 干掉重复呢?

 select *
    from (
        select *, cluster_sample(1) over(partition by  id) as flag
        from student_table 
        ) sub
    where flag = true;

随机抽样

0.00047147460303803655
0.8346089547661175
0.763442322501653
0.4278550224508415
0.672133090287509
0.25099721842026207
0.24351493979036573
0.5438010611309675
0.7853498113273409
0.25878882699589656

每次执行结果都是固定的.

那么随机抽样10%的数据, 就可以这么写:

select * from
(select *, 
        trunc(rand(),2)*100 as random 
from  student_table ) tmp
where random between 1 and 10 ; --[1,10] 约10%的数据
上一篇 下一篇

猜你喜欢

热点阅读