经典sql

一、连续登录问题

问题:1)、每个用户连续登录最大天数

2)、连续登录大于三天的用户数

分析:本质都是计算用户连续登录天数

方案一:利用排序窗口

sql 复制代码
select a.user_id
      ,a.date_rslt
      ,count(1) as cnt
from (
        select    
            t.user_id
            ,t.login_time
            ,date_sub(login_time, num) as date_rslt
         from (
                select 
                    user_id
                    ,login_time
                    ,row_number() over(partition by user_id order by login_time) as num
                from login_log
         ) t
      ) a
group by a.user_id,a.date_rslt

方案二、增量加全量

连续访问天数v_days(最新flag值为1,则v_days累加,否则为0)

历史最大访问天数max_days (从max_days、v_days中取最大值)

sql 复制代码
select 
    coaleasce(h.user_id,i.user_id) as user_id,
    if(i.user_id is not null,v_days+1,0) as v_days,
    greatest(max_days,if(i.user_id is not null,v_days+1,0)) as max_days
from
history_ds h
full join 
log_time i

扩展1:连续登录,中间间隔1天也算

sql 复制代码
select user_id
       ,group_id
       ,(datediff(max(login_date),min(login_date))+1) as continuous_login_days
  from (
      select 
            user_id
            ,login_date
            ,sum(if(date_diff>1,1,0)) over(partition by user_id order by login_date rows between unboundedpreceding and current row) as group_id
      from (
        select 
            user_id
            ,login_date
            ,datediff(login_date,last_login_date) as date_diff
        from (
            select 
                user_id
                ,login_date
                ,lag(login_date,1,'1970-01-01') over(partition by user_id order by login_date) as last_login_date
            from test_login
        )t1
    )t2
)t3
group by user_id
       ,group_id;

扩展2:断点排序

连续日期的数据对应的值发生变化,重新排序

sql 复制代码
select  
  a,
  b,
  row_number() over( partition by b,a_diff order by a) as c
from 
(
  select  
    a,
    b,
    a-num as a_diff
  from 
  (
   select 
     a,
     b,
     row_number() over( partition by b order by  a ) as num
   from t1 
  )tmp1
)tmp2
order by a; 
相关推荐
lizhihai_9921 小时前
股市学习心得—半导体12种核心材料
大数据·人工智能·学习
ZGi.ai21 小时前
智能客服系统设计:从工单分类到自动派单的工程实现
大数据·人工智能·分类
PaperData1 天前
2000-2023年地级市数字基础设施评价指标体系
大数据·网络·数据库·人工智能·数据分析·经管
Blockchain Learning1 天前
去中心化身份(DID)模型解析:区块链如何重塑身份管理?
大数据·去中心化·区块链
xcbrand1 天前
政府事业机构品牌策划公司哪家可靠
大数据·人工智能·python
程序鉴定师1 天前
如何选择合适的深圳小程序开发公司?
大数据·小程序
雪碧聊技术1 天前
组合查询(union)
数据库·sql
晨启AI1 天前
GPT-5.5 来了!OpenAI 最新提示词指南深度解读
大数据·人工智能·ai·提示词
地球资源数据云1 天前
中国陆地生态系统主要植物功能特征空间分布数据
大数据·数据库·人工智能·机器学习
金智维科技官方1 天前
AI智能体在7×24客服场景中的真实表现评估
大数据·人工智能·ai·rpa·智能体