Question

I have a table with ID and City as columns. I want to write a sql query that will return ID and count(ID) as columns where City = City and ID = ID.

I have this so far:

select N.ID, count(N.ID) as OpenCities
into #new2 
from #new N
where ...

the where is the part I'm having trouble with. Please help. Thank you.

Sample Data:

ID   |   City
=============
1      New York
1      Chicago
2      New Jersey
2      Chicago
2      Chicago
3      Miami
3      Miami
3      Miami
3      Miami
3      Tuscon

What I want returned:

ID   |   OpenCities
===================
2        2
3        4
Was it helpful?

Solution

Try grouping by id and city and only getting results with a count more than 1.

SELECT
    ID,
    count(1)
FROM Table
GROUP BY ID, City
HAVING count(1) > 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top