复杂sql-按【连续时间】分组(连续【登录】天数问题)

本文介绍如何使用Hive SQL通过窗口函数row_number()和日期操作来计算用户连续登录天数的方法,并提供了一个具体的数据示例及其实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文基于hive1.1.0-cdh5.12.1

示例数据如下:

userid

date

a

2021-01-01

a

2021-01-02

a

2021-01-03

a

2021-01-05

a

2021-01-06

b

2021-01-01

b

2021-01-04

要求:求每个用户每天连续登录的天数

参考结果:

userid

date

continuous_days

a

2021-01-01

3

a

2021-01-02

3

a

2021-01-03

3

a

2021-01-05

2

a

2021-01-06

2

b

2021-01-01

1

b

2021-01-04

1

参考实现:

with t as (
select 'a' as userid,to_date('2021-01-01') AS date union all
select 'a' as userid,to_date('2021-01-02') AS date union all
select 'a' as userid,to_date('2021-01-03') AS date union all
select 'a' as userid,to_date('2021-01-05') AS date union all
select 'a' as userid,to_date('2021-01-06') AS date union all
select 'b' as userid,to_date('2021-01-01') AS date union all
select 'b' as userid,to_date('2021-01-04') AS date 
)

select userid,date,rn,login_group,count(*) over(partition by userid,login_group) as continuous_days
from 
(
  select userid,date,rn,date_sub(date,rn) as login_group --这个相减是关键,将连续登录的行划分为同一组
  from 
  (
    select userid,date,row_number() over(partition by userid order by date) as rn from t
  ) t1
) t2
;

+---------+-------------+-----+--------------+------------------+--+
| userid  |    date     | rn  | login_group  | continuous_days  |
+---------+-------------+-----+--------------+------------------+--+
| a       | 2021-01-01  | 1   | 2020-12-31   | 3                |
| a       | 2021-01-02  | 2   | 2020-12-31   | 3                |
| a       | 2021-01-03  | 3   | 2020-12-31   | 3                |
| a       | 2021-01-05  | 4   | 2021-01-01   | 2                |
| a       | 2021-01-06  | 5   | 2021-01-01   | 2                |
| b       | 2021-01-04  | 2   | 2021-01-02   | 1                |
| b       | 2021-01-01  | 1   | 2020-12-31   | 1                |
+---------+-------------+-----+--------------+------------------+--+

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值