Search code examples
mysqlsqljoingoogle-bigquerywindow-functions

SQL: Calculating if an ID does NOT appear that did appear in the previous week only


I'm trying to figure out, on a rolling week-by-week basis, if a user attended or did not attend an event. However, I only want to include them as "did not attend" if they attended the previous week. For example if user attends Week 1 and Week 7, they would be only counted as "did not attend" for Weeks 2 and 8.

A simplified example of the data:

Table events which includes all event dates (weekly) and a unique event ID (time ascending)

Event_Date Event_ID
2023-03-09 1
2023-03-16 2
2023-03-23 3

And table users which shows the event dates and ID they attended:

Event_Date Event_ID User_ID
2023-03-09 1 151
2023-03-16 2 151
2023-03-23 3 151
2023-03-09 1 299
2023-03-23 3 299
2023-03-16 2 373

My question: How can I accomplish the following output using SQL? (User 299 attended Event 1 but not 2; User 373 attended Event 2 but not 3)

Missed_Event_Date Missed_Event_ID User_ID
2023-03-16 2 299
2023-03-23 3 373

I have tried using

SELECT      Event_ID + 1,
            User_ID
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM events WHERE u.Event_ID=e.Event_ID + 1)

which did not produce the correct output


Solution

  • Assuming that Event_ID increases by one, you might consider below as well.

    SELECT u.Event_ID + 1 AS Missed_Event_ID, u.User_ID
      FROM users u LEFT JOIN users v 
        ON u.User_ID = v.User_ID AND u.Event_ID + 1 = v.Event_ID
     WHERE v.Event_ID IS NULL AND u.Event_ID < (SELECT MAX(Event_ID) FROM events);
    
    -- Query results
    +-----------------+---------+
    | Missed_Event_ID | User_ID |
    +-----------------+---------+
    |               2 |     299 |
    |               3 |     373 |
    +-----------------+---------+