SQL查找重复值

时间:2013-09-30 21:24:46

标签: sql

我需要识别重复某个值的行。这是一个示例表:

COUNTRY         CITY
Italy           Milan
Englad          London
USA             New York
Canada          London
USA             Atlanta

查询应返回...

COUNTRY         CITY
Englad          London
Canada          London

...因为伦敦重复了。提前感谢您的帮助。

4 个答案:

答案 0 :(得分:3)

最简单的方法是使用子查询来计算每个城市出现的次数(并过滤掉那些出现多次的值):

SELECT * FROM Cities
WHERE City in
(
    SELECT City FROM Cities
    GROUP BY City
    HAVING COUNT(*) > 1
)

答案 1 :(得分:2)

select country, city 
from aTable
where city in
(
    select city
    from aTable
    group by city
    HAVING count(1) > 1
)

在此处试试:http://sqlfiddle.com/#!3/e9b1a/1

或者如果同一个城市& country combo出现两次,你只对这些国家不同的地方感兴趣:

select distinct country, city 
from aTable
where city in
(
    select city
    from aTable
    group by city
    HAVING count(distinct country) > 1
)

在此处试试:http://sqlfiddle.com/#!3/2dfaa/2

答案 2 :(得分:2)

如果您的DBMS支持窗口聚合。

SELECT COUNTRY,
       CITY
FROM   (SELECT COUNTRY,
               CITY,
               COUNT(*) OVER (PARTITION BY CITY) AS Cnt
        FROM   Cities) T
WHERE  Cnt > 1 

SQL Fiddle

答案 3 :(得分:0)

这个有效。从我的妻子那里得到它(她终于有时间研究这个)。以为你可能会感兴趣。

SELECT * FROM Cities 城市在哪里(选择城市)                 来自(SELECT City,                              伯爵(不同国家)                       来自城市                       GROUP BY City
                      有计数(不同的国家)> 1)a)