如何在相同的 table 上动态相交
How to intersect on same table dynamically
假设我有一个 table(城市,国家)。我只想获取所有国家/地区通用的城市。
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'
如果事先不知道国家/地区列表,我如何才能动态地实现这一点,最好不用游标。
你可以这样做:
select city
from #cities
group by city
having count(*) = (select count(distinct country) from #cities)
您好,或者您可以像这样使用自连接
SELECT 与城市 A 不同 A.CITY
在 A.CITY =B.CITY 和 A.COUNTRY<>B.COUNTRY;
加入城市 B
假设我有一个 table(城市,国家)。我只想获取所有国家/地区通用的城市。
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'
如果事先不知道国家/地区列表,我如何才能动态地实现这一点,最好不用游标。
你可以这样做:
select city
from #cities
group by city
having count(*) = (select count(distinct country) from #cities)
您好,或者您可以像这样使用自连接 SELECT 与城市 A 不同 A.CITY 在 A.CITY =B.CITY 和 A.COUNTRY<>B.COUNTRY;
加入城市 B