本文章旨在用于记录学习经验和便于交流 博主水平有限 如果文章中有任何错误 欢迎指出 博主不胜感激。(注:转载引用请注明出处)
连续问题:
如下数据为蚂蚁森林中用户领取的减少碳排放量,找出连续3天及以上减少碳排放量在100以上的用户。
id dt lowcarbon
1001 2021-12-12 123
1002 2021-12-12 45
1001 2021-12-13 43
1001 2021-12-13 45
1001 2021-12-13 23
1002 2021-12-14 45
1001 2021-12-14 230
1002 2021-12-15 45
1001 2021-12-15 23
… …
思路·:1 按照用户id和dt进行分组聚合 剔除排放量少于100的用户 2 对用户进行排序 3 使用dt减去排名的差值 4 按照差值进行分组 统计相同差值的个数 保留 个数大于3的用户
select
id,
flag,
count(*) ct
from (
select
id,
dt,
lowcarbon,
date_sub(dt,user_order) flag
from (
select
id,
dt,
lowcarbon,
rank() over(partition by id orderby dt) user_order
from (
select
id,
dt,
sum(lowcarbon) lowcarbon
from test1
group by id,dt
having lowcarvon>100
)t1
)t2
)t3
group by id,flag
having ct>-3
函数直达:date_sub()函数: