with data as (
select '2023-01-01' as dt ,'UserA' as user_name union all
select '2023-01-01' as dt ,'UserB' as user_name union all
select '2023-01-02' as dt ,'UserA' as user_name union all
select '2023-01-03' as dt ,'UserC' as user_name union all
select '2023-01-04' as dt ,'UserA' as user_name union all
select '2023-01-05' as dt ,'UserB' as user_name union all
select '2023-01-06' as dt ,'UserA' as user_name union all
select '2023-01-07' as dt ,'UserC' as user_name union all
select '2023-01-09' as dt ,'UserA' as user_name union all
select '2023-01-10' as dt ,'UserB' as user_name union all
select '2023-01-11' as dt ,'UserA' as user_name union all
select '2023-01-12' as dt ,'UserC' as user_name union all
select '2023-01-13' as dt ,'UserA' as user_name union all
select '2023-01-14' as dt ,'UserB' as user_name union all
select '2023-01-15' as dt ,'UserA' as user_name union all
select '2023-01-16' as dt ,'UserC' as user_name union all
select '2023-01-17' as dt ,'UserA' as user_name union all
select '2023-01-18' as dt ,'UserB' as user_name
)
select
t.dt,
date_add(t.dt, 7) dt_to,
count(distinct t.user_name) as cnt
from
(
select
d1.dt,
d2.user_name
from
data d1
join data d2
where
1 = 1
--and d1.dt > d2.dt
and datediff(d1.dt, d2.dt) <= 7
) t
group by
dt
----
大数据量不建议这样做