Reputation: 568
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:
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:
But besides being quiet inelegant I have not been able to make it work.
I would appraciate any advice.
Thank you!
Upvotes: 2
Views: 716
Reputation: 6685
I'm not sure if I understand the requirement - but let me confirm my understanding
Let's assume your 'upperDate' is 7 October. That means you would like to check that a user had done all of the following
Now, imagine three users, all who had logged in only once
Their results would be as follows
In other words - I think all you need to do is find the logins between your upperdate minus 30 days
, to upperdate minus 7 days
.
As such you wouldn't need a loop - the easiest check is
DECLARE @upperDate Datetime = '20201015';
DECLARE @activeSpan int = 30;
SELECT DISTINCT(UserID)
FROM logins
WHERE [Date] >= DATEADD(day, - @activeSpan, @upperDate)
AND [Date] <= DATEADD(day, -7, @upperDate);
Upvotes: 2