如何在sql中找到重复项

n9vozmp4  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(298)

我有一个选择3列的查询。每一行都应该是县、市和邮编的独特组合。然而,我有理由相信我在某处得到了一个复制品。我如何找到复制品?count()??这是在ms sql server中实现的。任何帮助都将不胜感激--杰森

SELECT  COUNTY, CITY, ZIP 
FROM MoratoriumLocations
WHERE MoratoriumID=20
ORDER BY County
c86crjj0

c86crjj01#

你可以用 group by 以及 having ```
SELECT COUNTY, CITY, ZIP
FROM MoratoriumLocations
WHERE MoratoriumID=20
GROUP BY COUNTY, CITY, ZIP
HAVING COUNT(1) >1
ORDER BY County

如果您想获得完整的行详细信息,可以将子查询与 `group by` 以及 `having` 声明

SELECT x.*
FROM MoratoriumLocations x
INNER JOIN(
SELECT COUNTY, CITY, ZIP
FROM MoratoriumLocations
WHERE MoratoriumID=20
GROUP BY COUNTY, CITY, ZIP
HAVING COUNT(1) >1
) dups ON dups.County = x.County
AND dups.City = x.City
AND dups.Zip = x.Zip

t40tm48m

t40tm48m2#

有关如何查找DUP,请参见preben的答案。
为了避免DUP,请考虑创建一个唯一索引

0vvn1miw

0vvn1miw3#

我建议窗口功能:

SELECT ml.*
FROM (SELECT ml.*, COUNT(*) OVER (PARTITION BY County, City, Zip) as cnt
      FROM MoratoriumLocations ml
      WHERE MoratoriumID = 20
     ) ml
ORDER BY cnt DESC, County, City, Zip;

这将显示包含重复项的完整行,这可以帮助您更好地理解它们。

相关问题