如果在另一列上聚合,则匹配具有特定计数的行

时间:2011-09-27 09:49:52

标签: sql join count

我有一个包含这些字段的表:Url, IP, input

我想检索具有不同输入的不同IP的所有网址(和相应的IP)

示例:

Url1, IP1, input1
Url2, IP2, input1
Url3, IP3, input1
Url1, IP4, input2
Url2, IP5, input2
Url3, IP3, input2
Url4, IP3, input2

我试图得到这样的结果:

Url1, IP1, input1
Url1, IP4, input2
Url2, IP2, input1
Url2, IP5, input2

因为Url3在不同的输入上得到相同的IP3,我不希望它在结果

另外,我不想要Url4,因为它只在input2

我搜索子查询和连接(在同一个表上),但最终在外部脚本中完成了它:有没有办法在SQL中直接执行它

2 个答案:

答案 0 :(得分:1)

尝试使用GROUP BY,HAVING和子选择:

create table your_table
(Url varchar(50),IP varchar(50), input varchar(50));


insert into your_table (Url, IP, input) values ('Url1', 'IP1', 'input1');
insert into your_table (Url, IP, input) values ('Url2', 'IP2', 'input1');
insert into your_table (Url, IP, input) values ('Url3', 'IP3', 'input1');
insert into your_table (Url, IP, input) values ('Url1', 'IP4', 'input2');
insert into your_table (Url, IP, input) values ('Url2', 'IP5', 'input2');
insert into your_table (Url, IP, input) values ('Url3', 'IP3', 'input2');



select *
from your_table
where (Url,IP) in
(
select Url, IP
from
(
select Url, IP, count(*)
from your_table
group by Url, IP
having count(*) = 1
) a
);

答案 1 :(得分:0)

GROUP BY会做

SELECT MIN(Url), IP, input
FROM   YourTable
GROUP BY
       IP, input
相关问题