[英]How to get list of latest event per Id and month based on date interval?
I have a table registering different event dates for unique identifiers - one row for each Id-event-date combination.我有一个表格,为唯一标识符注册不同的事件日期 - 每个 Id-event-date 组合一行。 Each unique identifier can have multiple dates, according to the number of events happening to that Id.根据发生在该 ID 上的事件数量,每个唯一标识符可以有多个日期。 There are no two events occurring on the same date for individual Ids.对于单个 ID,没有两个事件在同一日期发生。
First, I wanted to identify the unique Ids for which the latest event has occurred for more than 7 days to current date.首先,我想确定到当前日期已发生超过 7 天的最新事件的唯一 ID。 This is my working approach:这是我的工作方法:
WITH latest_event AS
(
SELECT Id,
date,
event,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY date DESC) AS row_number
FROM `table`
),
SELECT Id,
date,
event,
FROM latest_stage
WHERE row_number = 1
AND DATE_DIFF(CURRENT_DATE(),date, DAY) > 7
ORDER BY date
Now I would like to obtain the same information, but on a monthly basis, instead of just current date.现在我想获得相同的信息,但每月一次,而不仅仅是当前日期。 For instance for every month in 2021 and 2022, identify the number of unique Ids which, by the end of each month, did not have an event in the last 7 days.例如,对于 2021 年和 2022 年的每个月,确定在每个月底之前在过去 7 天内没有发生事件的唯一 ID 的数量。 I am struggling to understand how to do this calculation for every month in these two years.我很难理解如何在这两年中每个月进行此计算。
I am not sure this will work.我不确定这会奏效。 Please improve it yourself.请自行改进。
with tbl as
(Select cast(rand()*10 as int64) Id, date,"E" event from unnest(generate_date_array("2021-01-01","2022-09-23",interval 1 day)) as date)
select *,
date_trunc(date,month) as month_trunc,
lag(date) over last_date_window as last_date,
ifnull(date_diff(date, lag(date) over last_date_window,day),99) as diff,
max(date) over this_month_window as last_date_of_month
from tbl
qualify
ifnull(date_diff(date, lag(date) over last_date_window,day),99)>7
and date=max(date) over this_month_window
window
last_date_window as (partition by id order by date),
this_month_window as (partition by date_trunc(date,month))
order by date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.