Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding single instances of value SQL query

Status
Not open for further replies.

pkailas

Programmer
Jun 10, 2002
555
US
I have a zipcode database. I need to list out the Cities in which there is only one record.

The column is called "City" and the table is called "ZipCodes".

For some reason my brain isn't firing on all cylinders today!

_______
I love small animals, especially with a good brown gravy....
 
Never mind. I got it.

SELECT distinct City, StateCode, count(*) as theCount
FROM ZipCodes where country = 'USA' group by city, statecode order by statecode, city

_______
I love small animals, especially with a good brown gravy....
 
This query is not what you requested. For SQL Server 2005 and up
Code:
Select * from (select *, count(*) over (partition by City) as CityRecordsCount from myTable) where CityRecordsCount = 1
 
You don't need the distinct because your group by clause guarantees that the data will be distinct. If you want ony cities that are not duplicated (based on zip code) then you could use the having clause.

Code:
SELECT   City, StateCode, count(*) as theCount 
FROM     ZipCodes 
Where    country = 'USA'  
group by city, statecode 
Having   Count(*) = 1
order by statecode, city



-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top