查询获取少于3个城市的国家/地区名称

时间:2013-10-01 06:36:44

标签: sql sql-server tsql

我有两个名为country和city的表是关系表。

表格结构:

Country : CountryID CountryName

City : CityID CountryID CityName

其中两个表都包含一些数据。我想要一个国家少于3个城市的结果。

4 个答案:

答案 0 :(得分:1)

试试这个

select c.CountryID
from country c
left join city ci on c.CountryID=ci.CountryID
group by c.CountryID
having COUNT(c.CountryID)<3

答案 1 :(得分:1)

 select c1.CountryName 
 from country c1 left join city c2 on c1.CountryID=c2.CountryID
 group by c2.CountryID,c1.CountryName,c1.CountryID having count(*)<3

答案 2 :(得分:0)

SELECT co.CountryID, co.CountryName, COUNT(ci.CityID) as NumberOfCities
FROM Country co
LEFT JOIN City ci
ON
co.CountryID = ci.CountryID
GROUP BY co.CountryID, co.CountryName
HAVING COUNT(ci.CityID) < 3 

答案 3 :(得分:-2)

select * 
from country LEFT JOIN 
  (select CountryID, count(*) as cnt 
   from city 
   group by CountryID 
   having cnt<3) c ON country.CountryID =c.CountryID