I have a table registering different event dates for unique identifiers - one row for each Id-event-date combination. Each unique identifier can have multiple dates, according to the number of events happening to that Id. There are no two events occurring on the same date for individual Ids.
First, I wanted to identify the unique Ids for which the latest event has occurred for more than 7 days to current date. 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. I am struggling to understand how to do this calculation for every month in these two years.