Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select count / duplicates

I have a table with all U.S. zip codes. each row contains the city and state name for the zip code. I'm trying to get a list of cities that show up in multiple states. This wouldn't be a problem if there weren't X amount of zip codes in the same city...

So basically, I just want to the city in a state to count as 1 instead of it counting the city/state 7 times because there are 2+ zip codes in that city/state...

I'm not really sure how to do this. I know I need to use count but how do I tell the mysql to only count a given city/state combo as 1?

like image 971
mike Avatar asked Mar 25 '10 14:03

mike


People also ask

How do I count duplicates in SQL?

How do I count duplicate rows in SQL? Using the GROUP BY clause to group all rows by the target column(s) – i.e. the column(s) you want to check for duplicate values on. Using the COUNT function in the HAVING clause to check if any of the groups have more than 1 entry; those would be the duplicate values.

Does count (*) include duplicate values?

Answer. Yes, when using the COUNT() function on a column in SQL, it will include duplicate values by default. It essentially counts all rows for which there is a value in the column.


2 Answers

SELECT City, Count(City) As theCount
FROM (Select City, State From tblCityStateZips Group By City, State) As C
GROUP By City
HAVING COUNT Count(City) > 1

This would return all cities, with count, that were contained in more than one state.

Greenville 39
Greenwood 2
GreenBriar 3
etc.

like image 113
Patrick Karcher Avatar answered Sep 21 '22 15:09

Patrick Karcher


First group on state and city, then group the result on city:

select City
from (
  select State, City
  from ZipCode
  group by State, City
) x
group by City
having count(*) > 1
like image 42
Guffa Avatar answered Sep 21 '22 15:09

Guffa