154

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?

Anax
  • 9,122
  • 5
  • 34
  • 68
Mike
  • 2,195
  • 4
  • 15
  • 10

3 Answers3

314
 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
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
  • 25
    I love SQL because you get questions like "How do I count distinct user IDs" and the answer is just "`Count(Distinct user_id)`" – Tim Nov 13 '18 at 15:29
26

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
7

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168