最小达到某累积金额的日期
题目:现有表test,有三个字段分别为:user_id 用户id dt 日期 price 订单金额,计算一个消费者历史上首次在近30天周期内累积消费金额达到1w的日期。
分析:1.要求在30天周期内,累积消费金额达1w的日期,可以用sum(price) over(partition by user_id order by dt rows between 30preceding and current row)sum_price
2.然后查询最小达到1w金额的日期,用min(dt) ... where sum_price>=10000 ,记得根据用户分组
完整sql:
select t1.user_id,t1.dt,min(dt)
from(
select user_id,dt,sum(price)over(partition by user_id order by dt rows between 30 preceding and current row)sum_price
from test
)t1
where t1.sum_price >= 10000
group by t1.user_id