[英]count unique values in a group, and exclude already counted rows in mysql
I would like to count all unique visitors group by day.But i want to exclude the visitor if he has already visited any previous day.My sample table is as below 我想按天计算所有唯一身份访问者组。但如果访问者前一天已经访问过,我想将其排除在外。我的示例表如下
mysql> select * from visitor;
+-------+------------+--------------+
| user | visit_date | No Of Visits |
+-------+------------+--------------+
| user1 | 20150101 | 10 |
| user2 | 20150102 | 1 |
| user3 | 20150101 | 1 |
| user1 | 20150102 | 2 |
+-------+------------+--------------+
My requirement is to get a distinct count of user group by visit date but to exclude already visited user. 我的要求是按访问日期获得用户组的明确计数,但要排除已访问过的用户。
20150101 --> User1 and user 3 visited 20150101->访问了用户1和用户3
20150102 --> User 2 visited (Exclude user1 as he has already visited) 20150102 - >用户2访问(排除用户1,因为他已访问过)
+----------------------+------------+
| count(distinct user) | visit_date |
+----------------------+------------+
| 2 | 20150101 |
| 1 | 20150102 |
+----------------------+------------+
select visit_date, count(distinct user)
from visitors as v1
where not exists (
select 1
from visitors as v2
where
v2.user = v1.user
and v2.visit_date = date_sub(v1.visit_date, interval 1 day)
)
group by visit_date
or 要么
select v1.visit_date, count(distinct v1.user)
from
visitors as v1
left outer join visitors as v2
on v2.user = v1.user
and v2.visit_date = date_sub(v1.visit_date, interval 1 day)
where v2.user is null
group by v1.visit_date
Not really sure if DISTINCT
is actually necessary in the aggregate. 不确定DISTINCT
在聚合中是否真的是必要的。
select count(*),hr from (select user, min(visit_date)as hr from visitor v group by user) as data group by hr 选择count(*),hr(从(选择用户,min(visit_date)作为访问者v按用户v按小时分组)作为数据按hr分组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.