计算组中的唯一值,并排除mysql中已计数的行

时间:2015-02-11 06:49:21

标签: mysql

我想白天计算所有唯一身份访问者群体。但是如果他已经访问了前一天我想要排除访问者。我的样本表如下所示

mysql> select * from visitor;
+-------+------------+--------------+
| user  | visit_date | No Of Visits |
+-------+------------+--------------+
| user1 | 20150101   | 10           |
| user2 | 20150102   | 1            |
| user3 | 20150101   | 1            |
| user1 | 20150102   | 2            |
+-------+------------+--------------+

我的要求是按访问日期获得用户组的明确计数,但要排除已访问过的用户。

20150101 - >访问过User1和用户3

20150102 - >用户2访问过(排除了他已经访问过的用户1)

+----------------------+------------+
| count(distinct user) | visit_date |
+----------------------+------------+
|                    2 | 20150101   |
|                    1 | 20150102   |
+----------------------+------------+

2 个答案:

答案 0 :(得分:0)

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

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

不确定集合中是否确实需要DISTINCT

答案 1 :(得分:0)

解决

选择count(*),hr from(select user,min(visit_date)为hr       来自访客v       按用户分组)作为hr的数据组