假设表Geogrpahy中第一列为“State”,第二列为“城市”,如下所示:
State City
S1 C1
S2 C2
S3 C3
S4 C2
S1 C1
S2 C3
S3 C4
S9 C2
如何拥有多个城市的州?
如何与普通城市共建州?
发布于 2017-05-16 05:48:31
在您的情况下,州和城市组合在表中是多倍的,例如(S1,C1)。因此,首先将桌子分组,以区分这两种组合。
因此,查询有多个城市的州如下所示
SELECT States, COUNT(City) AS NoofCities
FROM (SELECT States, City
FROM Geogrpahy
GROUP BY States, City) AS TT
GROUP BY States having COUNT(City)>1
为了让其他州的城市也做以下的事情
select States,City from Geogrpahy as geography1 where City in (select City from Geogrpahy where Geogrpahy.States!=geography1.States)
同样,如果只想获得状态,则将其分组为状态。
发布于 2017-05-15 08:27:48
--Microsoft SQL Specific:
--States with multiple cities
SELECT [State] ,count (distinct [City]) as Cities_Count
FROM [dbo].[Geogrpahy]
group by [State]
having count (distinct [City]) > 1
--Cities in multiple States
select * from [Geogrpahy]
where [City] in (
select [City] from (
SELECT [City] ,count (distinct [State]) as State_Count
FROM [dbo].[Geogrpahy]
group by [City]
having count (distinct [State]) > 1) a)
order by City, [State]
发布于 2017-05-15 07:58:38
使用下面的查询获取具有多个城市的州
SELECT State , COUNT(*) AS NO_OF_City FROM Geogrpahy
GROUP BY State HAVING COUNT(*) > 1 ORDER BY State ;
https://stackoverflow.com/questions/43974108
复制相似问题