user_id score
101 45
102 40
103 35
104 30
105 25
表中的数据代表每一个用户和其对应的得分,user_id和score都不会有重复值。瓜分奖金的规则如下:按照score从高到低依次瓜分,每个人都能分走当前奖金池里面剩余奖金的一半,当奖金池里面剩余的奖金少于500时(不含),则停止瓜分奖金。
现在需要查询出所有分到奖金的user_id和其对应的奖金。
SQL解答:
这是拼多多的一个面试题,需要先进行一点数学层面的分析,把整个瓜分逻辑捋清楚之后不难。这里给出一种思考逻辑:假设奖金池的初始总奖金为n,那么第一名分到的奖金为n/2,第二名分到奖金n/4,第三名分到的奖金为n/8,依次类推第x名分到的奖金为n/2^x,然后计算即可。
select
user_id
,score
,1/power(2,rn)*3000 as prize
from
(
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
)t1
where 1/power(2,rn)*3000>=250
;
往期推荐