MySQL COUNT DISTINCT


144

我正在尝试收集昨天在我的客户服务中进行的不重复访问的次数,然后对它们进行计数。

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

由于某些原因,这会使用相同的站点ID提取多个结果。...我如何只提取并计算不同的site_id cp登录数?

Answers:


299
 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

17
我喜欢SQL,因为您会遇到“如何计算不同的用户ID”之类的问题,而答案只是“ Count(Distinct user_id)
Tim

23

总体

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

或每个站点

  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`

time结果中没有该列是没有意义的-因为您正在聚集行,所以显示一个特定的内容time是无关紧要的,除非它是the minmax您在后面。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.