AnswerBun.com

How do I find a duplicate in SQL

Stack Overflow Asked by Jason Livengood on December 16, 2021

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

3 Answers

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.

Answered by Gordon Linoff on December 16, 2021

See Preben's answer for how to find dups.

To avoid dups altogether consider creating an unique index.

Answered by Z.D. on December 16, 2021

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

Answered by Preben Huybrechts on December 16, 2021

Add your own answers!

Related Questions

how to count number of file with a matching pattern using python

2  Asked on February 16, 2021 by suryansh-mathur

 

R First Row By Group When Condition Is Met

4  Asked on February 16, 2021 by bvowe

   

C++ program won’t print anything with vectors?

2  Asked on February 16, 2021 by luckylone-official

 

What is damping for?

3  Asked on February 16, 2021 by lix

       

Spring 5 MVC not finding mapping to controller returning JSON

2  Asked on February 16, 2021 by gary-kephart

   

Pointer value in c

3  Asked on February 15, 2021 by gsoap

 

Memory allocation of map[int]interface{} vs map[int]struct{}

2  Asked on February 15, 2021 by gabriel-gonzalez

   

Does the “leftmost prefix rule” of Index applies to SQL Server?

2  Asked on February 15, 2021 by drillfreak100

   

How to add ArrayList to JsonObject in Kotlin

2  Asked on February 15, 2021 by rajitha-perera

   

How to get data from axios request?

1  Asked on February 15, 2021 by theyaxxe

   

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP