I am trying to count users created in a month, let’s say January 2015. Then I am trying to count users created as at January 31st, 2015. Then I am trying to count distinct user IDs that logged in during a month, which would also be January 2015. Then I am trying to count the total logins belonging to the distinct user IDs that logged in during January 2015.
The data is stored in 2 tables – users and auditlogins. The primary key for both the users and auditlogins table is userid.
If I wrote each query separately, I would have the following queries:
SELECT 'Jan 2015' AS 'Month',
COUNT(users.userid) AS 'Total at month end'
FROM users
WHERE users.datecreated < ('2015-02-01 00:00:00.000')
SELECT 'Jan 2015' AS 'Month',
COUNT(users.userid) AS 'User IDs created in Month'
FROM users
WHERE users.datecreated > ('2015-01-01 00:00:00.000') AND users.datecreated < ('2015-02-01 00:00:00.000')
SELECT 'Jan 2015' AS 'Month',
COUNT(DISTINCT auditlogins.userid) AS 'Unique User Logins in Month'
FROM auditlogins
WHERE auditlogins.logintime > ('2015-01-01 00:00:00.000') AND auditlogins.logintime < ('2015-02-01 00:00:00.000')
SELECT 'Jan 2015' AS 'Month',
COUNT(auditlogins.userid) AS 'Total Logins in Month'
FROM auditlogins
WHERE auditlogins.logintime > ('2015-01-01 00:00:00.000') AND auditlogins.logintime < ('2015-02-01 00:00:00.000')
What I really want is everything in one row. My final output would look like this:
Month Total at month end User IDs created in Month Unique User Logins in Month Total Logins in Month Jan-15 19,908 1,647 4,127 24,881
How do I do this? I have tried CASE WHEN and joining the tables, but I cannot seem to get a distinct count of userids logging on within a date range.
Your help is greatly appreciated as this is frustrating me to no end!