SQL:每个ID的最早和最新记录,也与其他ID相关



问题摘要

我有两个表,注册通知,其中包含注册和通知,其中每个通知都可以被视为唯一的,并具有ID。

如果注册发生在X之前和通知X-1之后,则可以将其归因于ID为X的通知。

我的数据如下:

注册

注册时间戳
2022-09-01
2022-09-05
2022-09-15
2022-09-24
2022-09-25
2022-09-29

如果我做对了,你需要当前通知和其预定之间的注册的最大值和最小值

select n.ID, n.NotificationTimestamp, min(s.SignupTimestamp) EarliestSignupTimestamp, max (s.SignupTimestamp) LatestSignupTimestamp
from Signup s
join (
select ID, NotificationTimestamp, lag(NotificationTimestamp) over(order by ID) prevNT
from Notifications
) n
on (s.SignupTimestamp > n.prevNT or n.prevNT is null) and s.SignupTimestamp < n.NotificationTimestamp
group by n.ID, n.NotificationTimestamp

最新更新