解决问题时如何与小组一起解决问题?

时间:2019-03-26 11:11:14

标签: sql

我在SQLZoo上遇到问题,陷入问题7,他们使用嵌套查询提供了解决方案,但是如何使用group by来实现呢? 链接到问题:https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial

我尝试过

select continent, name, area
from world
where area = (select max(area) from world
              group by continent);

但是响应是“子查询返回多于1行”

3 个答案:

答案 0 :(得分:1)

尝试一下

select continent, name, area
from world
where area IN (select max(area) from world
              group by continent);

答案 1 :(得分:0)

如果要使用=运算符,则需要一个相关的子查询以确保仅返回单行:

select w1.continent, w1.name, w1.area
from world w1
where w1.area = (select max(w2.area) 
                 from world w2
                 where w2.continent = w1.continent);

另一种选择是将IN运算符与两列一起使用,然后可以将group by保留在子选择中。

select continent, name, area
from world
where (continent, area) IN (select continent, max(area) 
                            from world
                            group by continent);

答案 2 :(得分:0)

您可以使用窗口功能对按大陆分组并按区域降序的行进行编号。

select continent, name, area
from (
    select 
    continent, 
    name, 
    area,
    row_number() over (partition by continent order by area desc) as rn
    from world ) world
    where world.rn = 1