简体   繁体   English

使用 SQL 为行分配加权值

[英]Assign weighted value to rows using SQL

I have a table of customers that I want to assign a test group.我有一张要分配测试组的客户表。 I want to assign a test group based on weighted values.我想根据加权值分配一个测试组。

Example:例子:

Group 1 - 50%
Group 2 - 25%
Group 3 - 20%
Group 4 - 5%

Result:结果:

customer_id客户ID group团体
1 1 group 1第 1 组
2 2 group 4第 4 组
3 3 group 1第 1 组
4 4 group 2第 2 组
5 5 group 1第 1 组
6 6 group 1第 1 组
7 7 group 2第 2 组
8 8 group 1第 1 组
9 9 group 3第 3 组
10 10 group 1第 1 组

If you shuffle the rows randomly you can then split based on the cumulative frequencies.如果您随机打乱行,则可以根据累积频率进行拆分。 While this works neatly the fractions are neat I'm not sure if this will meet the most general case you've got.虽然这可以很好地工作,但分数很整洁,但我不确定这是否会满足您所拥有的最普遍的情况。

with data as (
    select *,
        count(*) over () * 1.0 as cnt,
        row_number() over (order by random()) * 1.0 as rn
    from T
)
select customer_id,
    case when rn / cnt <= 0.50 then 'Group 1'
         when rn / cnt <= 0.75 then 'Group 2'
         when rn / cnt <= 0.95 then 'Group 3'
         when rn / cnt <= 1.00 then 'Group 4'
    end as grp
from data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM