首页 / 自学资源

SQL面试题挑战03:奖金瓜分问题(拼多多)

发布时间:2023-11-20 12:37:54

问题:在活动大促中,有玩游戏瓜分奖金环节。现有奖金池为3000元,代表奖金池中的初始额度。用户的分数信息如下:

user_id  score101       45102       40103       35104       30105       25

表中的数据代表每一个用户和其对应的得分,user_id和score都不会有重复值。瓜分奖金的规则如下:按照score从高到低依次瓜分,每个人都能分走当前奖金池里面剩余奖金的一半,当奖金池里面剩余的奖金少于500时(不含),则停止瓜分奖金。

现在需要查询出所有分到奖金的user_id和其对应的奖金。

SQL解答:

这是拼多多的一个面试题,需要先进行一点数学层面的分析,把整个瓜分逻辑捋清楚之后不难。这里给出一种思考逻辑:假设奖金池的初始总奖金为n,那么第一名分到的奖金为n/2,第二名分到奖金n/4,第三名分到的奖金为n/8,依次类推第x名分到的奖金为n/2^x,然后计算即可。

selectuser_id,score,1/power(2,rn)*3000 as prizefrom(    select    user_id    ,score    ,row_number() over(order by score desc) as rn    from    (        select 101 as user_id,45 as score        union all        select 102 as user_id,40 as score        union all        select 103 as user_id,35 as score        union all        select 104 as user_id,30 as score        union all        select 105 as user_id,25 as score    )t1)t1where 1/power(2,rn)*3000>=250;

往期推荐



相关推荐