Skip to content
Advertisement

How do I find a duplicate in SQL

I have a query that selects 3 columns. Each row row should be a unique combination of county, city,and zip. However, I have reason to believe I’m getting a duplicate somewhere. How do I find the duplicate ? COUNT() ?? This in MS SQL Server . Any help would be most appreciated. –Jason

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

Advertisement

Answer

You coul use group by and having

SELECT  COUNTY, CITY, ZIP 
FROM MoratoriumLocations
WHERE MoratoriumID=20
GROUP BY COUNTY, CITY, ZIP
HAVING COUNT(1) >1
ORDER BY County

If you want to get the full row details you can use a sub query in combination with the group by and having statements

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement