SQL:查找重复项,使用不同的字段

时间:2015-09-29 07:36:05

标签: sql duplicates ms-access-2010

我必须在Access表中找到重复项,其中一个字段不同。 我将尝试解释:假设有这个数据集

ID  Country     CountryB        Customer 
====================================================
1   Italy       Austria         James
2   Italy       Austria         James
3   USA         Austria         James

我必须查找具有重复的CountryB和Customer的所有记录,但具有不同的Country。

例如,根据上述数据,ID 1和2 NOT 重复(因为它们来自同一个国家/地区),而1和3(或2和3)是。 最好的"我得到的查询是以下一个:

SELECT COUNT(*),  CountryB, Customer FROM
(SELECT MIN(ID) as MinID, Country, CountryB, Customer FROM myTable GROUP BY Country, CountryB, Customer)
GROUP BY  CountryB, Customer
HAVING COUNT(*)>1

无论如何,我不确定这是否是最明智的选择。 此外,因为我需要"标记"所有的重复,我必须做更多的事情,像这样:

SELECT ID, a.Country, a.CountryB, a.Customer FROM  myTable a
INNER JOIN
(
SELECT COUNT(*),  CountryB, Customer FROM
(SELECT MIN(ID) as MinID, Country, CountryB, Customer FROM myTable GROUP BY Country, CountryB, Customer)
GROUP BY  CountryB, Customer
HAVING COUNT(*)>1
) dt
ON a.Country=dt.Country and a.CountryB=dt.CountryB and a.Customer=dt.Customer

非常感谢任何建议这种方法。

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。 这个答案是正确的解决方案:

SELECT DISTINCT HAVING Count unique conditions

改编自此版本,因为我使用的是Access 2010:

Count Distinct in a Group By aggregate function in Access 2007 SQL

因此,在我上面的示例表中,我可以使用此查询来查找重复记录:

SELECT CountryB, Customer, Count(cd.Country)
FROM (SELECT DISTINCT Country, CountryB, Customer FROM myTable) AS cd 
GROUP BY CountryB, Customer
HAVING COUNT(*) > 1

或此查询以查找重复记录的所有ID:

SELECT ID FROM myTable a INNER JOIN
(
SELECT CountryB, Customer, Count(cd.Country)
FROM (SELECT DISTINCT Country, CountryB, Customer FROM myTable) AS cd 
GROUP BY CountryB, Customer
HAVING COUNT(*) > 1
) dt
ON a.CountryB=dt.CountryB AND a.Customer=dt.Customer