Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to intersect on same table dynamically

Say I have a table (city, country). I want to only get cities that are common in all countries.

create table #cities(city nvarchar(10), country nvarchar(10))

insert into #cities(city, country)
select 'NY', 'US' UNION
select 'London', 'UK' UNION
select 'London', 'US'


select city from #cities where country = 'US'
intersect
select city from #cities where country = 'UK'

How can I achieve this dynamically and preferably without cursors if the list of countries is not known upfront.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do:

select city
from #cities
group by city
having count(*) = (select count(distinct country) from #cities)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading