-1

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
Jason Livengood
  • 117
  • 1
  • 3
  • 10

3 Answers3

0

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
Preben Huybrechts
  • 5,853
  • 2
  • 27
  • 63
0

See Preben's answer for how to find dups.

To avoid dups altogether consider creating an unique index.

Z .
  • 12,657
  • 1
  • 31
  • 56
0

I would suggest window functions:

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;

This will show the complete rows with duplicates, which can help you understand them better.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786