Using GROUP BY and HAVING./ja

From SQLZOO
Revision as of 18:55, 18 April 2018 by Kobashi.kaz (talk | contribs)
Jump to navigation Jump to search
Language:Project:Language policy [[:{{#invoke:String|sub|Using GROUP BY and HAVING./ja
 |1
 |Expression error: Unrecognized punctuation character "{".
}}|English]]

世界の国のプロフィール

GROUP BYHAVING

GROUP BY 節で SUMCOUNT のような集計関数を使うと、それぞれのグループに共通の値になる。 GROUP BY continent を指定すると、異なる値のcontinentが1行づつ表示される。 continent以外のすべての列(フィールド)は SUMCOUNT などの集計関数で1行にまとめる必要がある。

HAVING 節(の条件)は表示するグループを取り除く。 WHERE 節(の条件)は行(レコード)を集計する前に取り除く。 HAVING 節は集計後(の結果を使って)、取り除く。

ORDER BY 節は特定の列を参照して場所を決める。

For each continent show the number of countries:

world(name, continent, area, population, gdp)
SELECT continent, COUNT(name)
  FROM world
 GROUP BY continent
SELECT continent, COUNT(name)
  FROM world
 GROUP BY continent

For each continent show the total population:

world(name, continent, area, population, gdp)
SELECT continent, SUM(population)
  FROM world
 GROUP BY continent
SELECT continent, SUM(population)
  FROM world
 GROUP BY continent

WHERE and GROUP BY. The WHERE filter takes place before the aggregating function. For each relevant continent show the number of countries that has a population of at least 200000000.

SELECT continent, COUNT(name)
  FROM world
 WHERE population>200000000
 GROUP BY continent
SELECT continent, COUNT(name)
  FROM world
 WHERE population>200000000
 GROUP BY continent

GROUP BY and HAVING. The HAVING clause is tested after the GROUP BY. You can test the aggregated values with a HAVING clause. Show the total population of those continents with a total population of at least half a billion.

SELECT continent, SUM(population)
  FROM world
 GROUP BY continent
HAVING SUM(population)>500000000
SELECT continent, SUM(population)
  FROM world
 GROUP BY continent
HAVING SUM(population)>500000000