4

I have a table user_login with two rows, userId and tstamp (user id and timestamp of login).

Counting the number of logins is simple:

SELECT userId, COUNT(*) as logins FROM user_login GROUP BY userId;

Counting the number of logins before a certain date (e.g. Jan 1 2018) is also simple:

SELECT userId
     , COUNT(*) as loginsBeforeJan1 
  FROM user_login 
 WHERE tstamp < '2018-01-01' 
 GROUP 
    BY userId;

How can I have both results in one table? I tried

SELECT userId
     , COUNT(*) as logins
     , COUNT(IF(tstamp < '2018-01-01',1,0)) loginsBeforeJan1 
  FROM user_login 
 GROUP 
    BY userId;

but both the logins and loginsBeforeJan1 are identical.

How can I modify the query to produce the result I want?

0

2 Answers 2

5

You could use a sum (and group by)

SELECT userId, COUNT(*) as logins, sum(IF(tstamp < '2018-01-01',1,0)) as loginsBeforeJan1 
FROM user_login
group by userId;
Sign up to request clarification or add additional context in comments.

2 Comments

Oops, I forgot to add the GROUP BY! I'll edit my question
Ok .. for group by but you should use sum and not count
0

Try using the WHERE clause instead of the IF statement in your query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.