5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLZOO「SELECT within SELECT Tutorial」 回答集

Last updated at Posted at 2018-09-08

###<2020/08/15 追記>
現在、SQLの学習をSQLZOOで開始するのはあまりお勧めできません。
別のサービスの活用をご検討ください。


SQLZOOの「SELECT within SELECT Tutorial」の回答集です。
前回の「SELECT from Nobel Tutorial」の続編です。


  1. Bigger than Russia
SELECT name FROM world
  WHERE population >
     (SELECT population FROM world
      WHERE name='Russia')

国名を変えるだけ

2 . Richer than UK

SELECT name
FROM world
WHERE continent ='Europe'
  AND gdp/population >
     (SELECT gdp/population FROM world
      WHERE name='United Kingdom')

3 . Neighbours of Argentina and Australia

SELECT name, continent
FROM world
WHERE continent IN
    (SELECT continent
     FROM world
     WHERE name IN ('Argentina', 'Australia'))
ORDER BY name

4 . Between Canada and Poland

SELECT name, population
FROM world
WHERE population >
    (SELECT population
     FROM world
     WHERE name = 'Canada')
    AND
      population <
        (SELECT population
         FROM world
         WHERE name = 'Poland')

BETWEEN句だと失敗しました。~~(できるはずですよね..?)~~BETWEEN句だとA以上B以下で、A,Bを含む形になってしまうためNG。

5 . Percentages of Germany

SELECT name, CONCAT(ROUND(population/
    (SELECT population
     FROM world
     WHERE name = 'Germany')
   *100, 0),'%')
FROM world
WHERE continent = 'Europe'

多重構造でややこしいのですが、個別に見ていきましょう。

ROUND(数値,0)
→数値を小数点以下第一位で四捨五入する

CONCAT(a,b)
→aとbを繋げて「ab」と表示。今回の場合はROUNDした数値に%をつける形。

6 . Bigger than every country in Europe

SELECT name
FROM world
WHERE gdp > ALL
    (SELECT gdp
     FROM world
     WHERE continent = 'Europe' AND gdp > 0)

ALLで特定数値との比較なくすべてを抽出
NULL値を除く処理も加えている。

7 . Largest in each continent

SELECT continent, name, area FROM world x
  WHERE area >= ALL
    (SELECT area FROM world y
        WHERE y.continent=x.continent
          AND area > 0)

クエリのテーブルをx、サブクエリのテーブルをyとして
y.continent=x.continentで両テーブルの一致を探している。

8 . First country of each continent (alphabetically)

SELECT continent, min(name)
FROM world
GROUP BY continent

文字列カラムに対してmin()を使うと、アルファベット順に最初のもの、となります。

9 . Difficult Questions That Utilize Techniques Not Covered In Prior Sections

SELECT name, continent
FROM world x 
WHERE population/3 >= ALL
(SELECT population
FROM world y
WHERE y.continent=x.continent
AND x.name != y.name)

###続きはこちら

SQLZOO 「SUM and COUNT」 回答集

5
3
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?