I have a Login Table like this:
Date,UserID
2020-08-01,1
2020-09-01,1
2020-09-07,2
2020-10-01,3
2020-10-12,4
2020-10-25,1
Basically, every time a user logins to my application, it register the date
and the userID
. I need to know the number of active users. To me an active user is one that has login in the previous thirty days of every day in the last week. For instance, let's say we are counting this week which goes from 2020-10-09 (October 9 2020) to 2020-10-15 (October 15 2020). Then I would go like this:
Check UserID = 1:
- Has user login anytime between ('2020-10-09' - 30) and '2020-10-09'
- Has user login anytime between ('2020-10-10' - 30) and '2020-10-10'
And so on until 2020-10-15
Then, it goes the same for each user ID.
In other words, I check the number of users that have login in a sliding Window of 30 days during a week. I hope this makes sense.
This is what I had in mind:
DROP TABLE IF EXISTS #ActiveUsers
CREATE TABLE #ActiveUsers (UserID bigint)
DECLARE @lowerDate Datetime='2020-10-09'
DECLARE @upperDate Datetime='2020-10-15'
DECLARE @activeSpan int=30
WHILE(@lowerDate <= @upperDate)
BEGIN
SELECT e.UserID INTO #ActiveUsers FROM
(SELECT DISTINCT(UserID) FROM logins WHERE Date >= (@lowerDate - @activeSpan)) AS e
WHERE e.UserID NOT IN (SELECT UserID FROM #ActiveUsers)
SET @lowerDate = @lowerDate + 1
END
PRINT SELECT COUNT(*) FROM #ActiveUsers
My reasoning was like this:
- Check unique UserIDs in the timeframe.
- Insert the unique ones in the temporary table as ling as they have not been previously inserted
- Count the total after looping through the selected dates.
But besides being quiet inelegant I have not been able to make it work.
I would appraciate any advice.
Thank you!