Skip to main content

LeetCode 1107. New Users Daily Count SQL Solution

Problem

LeetCode SQL Problem

  1. New Users Daily Count

Traffic table

user_idactivityactivity_date
1login2019-05-01
1homepage2019-05-01
1logout2019-05-01
2login2019-06-21
2logout2019-06-21
3login2019-01-01
3jobs2019-01-01
3logout2019-01-01
4login2019-06-21
4groups2019-06-21
4logout2019-06-21
5login2019-03-01
5logout2019-03-01
5login2019-06-21
5logout2019-06-21

Solution

New Users Daily Count
SET @today = '2019-06-30';
SET @three_months_ago = timestampadd(day, - 90, @today);

-- For every date within at most 90 days from today:
-- Report the number of users that logged in for the first time on that date.
SELECT T.activity_date AS login_date
,count(DISTINCT T.user_id) AS user_count
FROM Traffic AS T
WHERE T.activity = 'login'
AND T.activity_date >= @three_months_ago -- Within at most 90 days from today
AND T.user_id NOT IN (
-- Get distinct user_id values that have logged in more than 3 months ago
SELECT DISTINCT user_id
FROM Traffic
WHERE activity_date < @three_months_ago
AND activity = 'login'
)
GROUP BY T.activity_date
ORDER By T.activity_date

Query Output

login_dateuser_count
2019-05-011
2019-06-212