不使用distinct关键字进行选择

3

我只想在过去7天中,至少有5个不同的客户端使用同一个IP地址时,选择该IP地址。但结果是错误的。

table_1
customer ip        date
1        0.0.0.0  15.11.2019
2        0.0.0.0  11.11.2019
3        0.0.0.0  09.11.2019
4        0.0.0.0  10.11.2019

table_2
customer ip       date
1        0.0.0.0  15.11.2019
6        1.2.2.2  11.11.2019
4        0.0.0.0  09.11.2019
8        0.0.0.0  10.11.2019
9        5.5.5.5  12.11.2019

结果应该是0.0.0.0, 因为客户1、2、3、4和8在过去的7天内使用了相同的IP地址。
SELECT y.ip,x.customer 
         from table_1 x
         inner join 
         table_2 y
         on y.ip = x.ip
         WHERE x.DATE > SYSDATE - 7
         group by y.ip,y.customer
         Having Count(y.customer)>=5

1
你说的“使用相同的IP”是什么意思?一个不起作用的查询并不能很好地解释。提供示例数据和期望的结果会更有帮助。 - Gordon Linoff
1
你不应该按顾客分组。 - Randy Slavey
2个回答

2

尝试使用distinct count,如下所示:

SELECT y.ip
         from table_1 x
         inner join 
         table_2 y
         on y.ip = x.ip
         WHERE x.DATE > SYSDATE - 7
         group by y.ip
         Having Count(distinct y.customer)>=5

2

从您的样本数据来看,您的数据似乎分布在具有相同结构的两个表中。如果是这样,您需要union all这两个表(而不是将它们连接起来),然后进行聚合:

select t.ip
from (
    select t1.customer, t1.ip, t1.date from table_1 t1
    union all 
    select t2.customer, t2.ip, t2.date from table_2 t2
) t
where t.date > sysdate - 7
group by t.ip
having count(distinct t.customer) >= 5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接