I have a table that stores userid, sessionid and datetime. The table stores data when a user is logged into a device and stores the user, session, and datetime. There can be multiple entries with one userid and sessionid combination. For example:
USERID | SESSIONID | DATE
abcd | 1234 | 2020-05-14 10:30:00
abcd | 1234 | 2020-05-14 10:32:00
abcd | 1234 | 2020-05-14 10:35:00
abcd | 1234 | 2020-05-14 11:32:00
abcd | 1234 | 2020-05-14 11:39:00
I am trying to combine these rows into a new table based on initial datetime up to datetime + x for the same session and user. The initial datetime moves if a date exceeds datetime+x. So if x is 30 minutes any date from start to datetime + 30min would be one row. If a date is greater than datetime + 30min it becomes the new start datetime and you perform the datetime+x until all dates have been looked at for a sessionid and userid combination.
The output of the example table should be:
USERID | SESSIONID | START_SESSION_DATE | END_SESSION_DATE
abcd | 1234 | 2020-05-14 10:30:00 | 2020-05-14 10:35:00
abcd | 1234 | 2020-05-14 11:32:00 | 2020-05-14 11:39:00
I am not sure how to achieve this using only SQL. I was going to create a stored procedure to perform all the logic in javascript and then insert into the new table in Snowflake but that will be very slow and it won't scale. Thanks in advance.