在from子句中使用带有内连接的子查询?

时间:2016-11-21 00:13:01

标签: sql oracle11g subquery

我正在尝试创建一个表,其中一列包含国家/地区,下一列是官方国家/地区的数量。基本上,一行可能会说32个国家有2种官方语言,28种有3种官方语言等等。

到目前为止,我已经制作了一张表格,列出了每个国家/地区的官方语言数量。

select c.name, count(l.language) number_of_languages from world.country c 
inner join (select countrycode, language, isofficial from
world.countrylanguage where isofficial='T') l on c.code=l.countrycode group
by c.name order by count(l.language)

以下是结果示例:

NAME                                                 NUMBER_OF_LANGUAGES
---------------------------------------------------- -------------------
Lesotho                                                                2
Sri Lanka                                                              2
Canada                                                                 2
Singapore                                                              3
Belgium                                                                3
Bolivia                                                                3

1 个答案:

答案 0 :(得分:0)

首先,您的查询可以简化。它不需要使用子查询:

select c.name, count(cl.language) as number_of_languages
from world.country c inner join
     world.countrylanguage cl
     on c.code = cl.countrycode
where cl.isofficial = 'T'
group by c.name
order by count(cl.language);

接下来,将其用作子查询:

select number_of_languages, count(*)
from (select c.name, count(cl.language) as number_of_languages
      from world.country c inner join
           world.countrylanguage cl
           on c.code = cl.countrycode
      where cl.isofficial = 'T'
      group by c.name
     ) cl
group by number_of_languages
order by number_of_languages;