Jason
Jason

Reputation: 851

mysql - filter query result based on count of one column's value?

I am running the following mysql query:

SELECT visitnum, userid
FROM user_visit 
WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'

Which returns me the following results:

visitnum   userid
2010       60265
2011       60264
2012       60264
2013       60268
2014       60269
2015       60269
2016       60269

As you can see, this means the user 60265 and 60268 has one visit; user 60264 has two visits and user 60269 has three visits.

Now - how do I modify my mysql query so that it returns me only the rows associated with users that only visit ONCE? In other words, I expect my query to return me the following result:

    visitnum   userid
    2010       60265
    2013       60268

And how do I modify the query to return me only the rows that associated with users that only visit TWICE? like this:

 visitnum   userid
 2011       60264
 2012       60264

Upvotes: 0

Views: 4550

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

You can use this trick:

SELECT max(visitnum) as visitnum, userid
FROM user_visit 
WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'
GROUP BY usserid
HAVING COUNT(*) = 1;

The trick here is that MAX(visitnum) is the one-and-only visit number, when there is only one row in the group.

An alternative way that doesn't use GROUP BY is:

select uv.*
from user_visits uv
where not exists (select 1
                  from user_visits uv2
                  where uv2.userid = uv.userid and uv.visitnum <> uv2.visitnum
                 );

This should have better performance, if you have in an index on user_visits(userid, visitnum).

Upvotes: 2

Luca
Luca

Reputation: 322

SELECT visitnum, userid
FROM user_visit
WHERE userid IN (
    SELECT userid
    FROM user_visit 
    WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'
    GROUP BY userid
    HAVING COUNT(*) = 2
)

Upvotes: 2

Related Questions