MySQL COUNT DISTINCT

时间:2011-04-20 23:03:23

标签: mysql

我试图在昨天收集我的cp中的不同访问次数,然后计算它们。

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登录?

3 个答案:

答案 0 :(得分:276)

 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

答案 1 :(得分:20)

总体

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是不相关的,除非它是min或{{ 1}}你在追求。

答案 2 :(得分:7)

您需要使用group by子句。

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id