MySQL COUNT DISTINCT

Mike picture Mike · Apr 21, 2011 · Viewed 318.6k times · Source

I'm trying to collect the number of distinct visits in my cp yesterday, then count them.

SELECT
    DISTINCT `user_id` as user,
    `site_id` as site,
    `ts` as time
FROM
    `cp_visits`
WHERE
    ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

For some reason this is pulling multiple results with the same site id....how do i only pull and count the distinct site_id cp logins?

Answer

ypercubeᵀᴹ picture ypercubeᵀᴹ · Apr 21, 2011
 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id