经典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; 
相关推荐
用户8307196840829 小时前
Java 告别繁琐数据统计代码!MySQL 8 窗口函数真香
java·sql·mysql
代码匠心1 天前
从零开始学Flink:Flink SQL四大Join解析
大数据·flink·flink sql·大数据处理
武子康2 天前
大数据-242 离线数仓 - DataX 实战:MySQL 全量/增量导入 HDFS + Hive 分区(离线数仓 ODS
大数据·后端·apache hive
SelectDB3 天前
易车 × Apache Doris:构建湖仓一体新架构,加速 AI 业务融合实践
大数据·agent·mcp
武子康4 天前
大数据-241 离线数仓 - 实战:电商核心交易数据模型与 MySQL 源表设计(订单/商品/品类/店铺/支付)
大数据·后端·mysql
IvanCodes4 天前
一、消息队列理论基础与Kafka架构价值解析
大数据·后端·kafka
爱可生开源社区4 天前
MiniMax M2.5 的 SQL 能力令人惊艳!
sql·llm
Nyarlathotep01134 天前
事务隔离级别
sql·mysql
武子康5 天前
大数据-240 离线数仓 - 广告业务 Hive ADS 实战:DataX 将 HDFS 分区表导出到 MySQL
大数据·后端·apache hive
Nyarlathotep01135 天前
SQL的事务控制
sql·mysql