MySQL COUNT DISTINCT

我试图在昨天收集我的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 CPlogin?

  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 

总体

 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是不相关的,除非它是minmax

你需要使用group by子句。

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