views:

55

answers:

2

Hello, I have a zipcode table. I want to look through this table and find every zipcode that is in it twice. The table does have a primary key set on it(zipcode_rid). How would I do this?

Also, I am aware that there are official multi-state/city/county zipcodes. That is what I'm wishing to find.

My table structure is like so:

  • zipcode_rid (int, unique, primary key)
  • zipcode (int)
  • city (varchar(50))
  • state (varchar(50))
  • county (varchar(50))

The database software I am using is Sql Server 2008 Express

+6  A: 

To get a list of zipcodes with duplicates, use:

  SELECT t.zipcode
    FROM TABLE t
GROUP BY t.zipcode
  HAVING COUNT(t.zipcode) > 1
OMG Ponies
+3  A: 

Here is a query that gives you all the zip codes that occur in the table twice. You can change the "= 2" portion to be "> 1" or whathaveyou. I've included the COUNT() in there because if you use ">1" you can see exactly how many times it appears.

SELECT
    COUNT(zipcode_rid) AS No_of_Zipcodes
    ,zipcode
FROM
    Zipcodes
GROUP BY
    zipcode
HAVING
    COUNT(zipcode_rid) = 2
fortheworld
If there's more than two duplicates, the zipcode won't be displayed if you use `HAVING COUNT(..) = 2`
OMG Ponies
@OMG Ponies - His question asked to see zipcodes that appeared in there twice. I also added the info about "> 1" to see those that appear in there twice, or more than twice.
fortheworld
Both of you are correct, but @OMG didn't include the `count` selection which makes this marginally better.. plus I like giving rep to the guys with <20k of rep :)
Earlz