I have a table that records all user cross-profile visits and I need to get the count of distinct visits and the count of new visits to a specified profile (:user_id) since the specified UNIX timestamp (:time).
id | user_id | visitor_id | time (unix)
====+==========+============+=============
1 | 1 | 5 | 1300000000
2 | 1 | 5 | 1300000010
3 | 1 | 8 | 1300000015
4 | 1 | 9 | 1300000020
5 | 1 | 9 | 1300000025
6 | 1 | 9 | 1300000030
So far I was only able to get the count of total visits, but am unable to get the new ones.
SELECT COUNT(DISTINCT v.visitor_id) AS total, SUM(v.time > 1300000012) AS new FROM profile_visits v WHERE v.user_id = 1
returns
total | new
============
3 | 4
but the required result is
total | new
============
3 | 2
You probably want
SUM(v.time > 1300000012) AS new.The expression is either 0 or 1.
COUNT()will count 0 as happily as 1. ButSUM()will “count” only the 1’s.Re your comment:
The
SUM()of the inner query counts new visits per visitor. TheSUM()of the outer query gives the total new visits for all visitors.