合并两个大小不同的SQL查询,因为

时间:2019-01-22 17:13:27

标签: sql oracle

我有两个SQL查询。

在其中一个中,我搜索了每个国家/地区中有多少座城市,并对所有少于6个城市的城市进行了过滤。

在第二个中,我搜索首都中有多少人口,并对所有人口少于500000的人口进行过滤。

我正在寻找的结果是搜索数据库中有6个以上城市且居住人口少于500000的所有国家,因为它们的大小不同,我似乎无法团结起来

select c.name, count(ci.name) as states_in_country
from country c, city ci
where c.code=ci.country 
group by c.name
having count(ci.name)>5 
;

select c.name, c.capital, ci.population
from country c, city ci
where c.capital=ci.name and ci.population>500000
;

我想像

select c.name, count(ci.name) as states_in_country, ci.population
from country c, city ci
where c.code=ci.country and c.capital=ci.name
group by c.name
having count(ci.name)>5 
;

但这显示城市的计数器仅为1。首都。

谢谢

4 个答案:

答案 0 :(得分:0)

您似乎不喜欢您尝试过的查询

select c.name 
from country 
where c.name NOT IN (
  select c.name
  from country c
  INNER JOIN city ci ON c.code=ci.country 
  group by c.name
  having count(ci.name)>5 
  ;

)  
and NOT IN (
  select c.name
  from country c
  INNER JOIN city ci ON c.capital=ci.name and ci.population>500000
)

答案 1 :(得分:0)

加入应该可以完成工作:

pow(rgb, 2.2)

答案 2 :(得分:0)

这是一个可能有效的查询。请注意以下事实:您提到的人口少于,并且您正在使用的查询> 500000大于。因此,请确保您实际上需要的东西更少。

select c.name, 
       cyCapital.name as capital,
       cyCapital.population as capPop,
       count(cy.*) cities
  from country c
         inner join city cy
           on c.code = cy.country
            and cy.population < 500000
         left join city cyCapital
           on c.code = cyCapital.country
           and c.capital = cyCapital.name
group by c.name,
         cyCapital.name as capital,
         cyCapital.population as capPop
having count(cy.*) > 5

答案 3 :(得分:0)

六个城市以上且居民少于50万的国家:

select country
from city
group by country
having count(*) > 6 and sum(population) < 500000;

拥有六个以上城市且至少一个居民少于50万的国家:

select country
from city
group by country
having count(*) > 6 
  and count(case when population < 500000 then 1 end) > 0;

拥有六个以上城市且所有居民少于500000的国家:

select country
from city
group by country
having count(*) > 6 
  and count(case when population >= 500000 then 1 end) = 0;

六个城市以上且城市人口不到50万的国家:

select c.code
from country c on ci.country = c.code
join city ci
group by c.code
having count(*) > 6 
  and count(case when c.capital = ci.name and ci.population < 500000 then 1 end) = 1;

好吧,你明白了...