SUM and COUNT/zh

From SQLZOO
Jump to: navigation, search
Language: English  • 中文

全球統計:群組函數

此教程是有關群組函數,例如COUNT, SUM 和 AVG。群組函數把多個數值運算,得出結果只有一個數值。例如SUM函數會把數值2,4,和5運算成結果11。

namecontinentarea populationgdp
AfghanistanAsia6522302550010020343000000
AlbaniaEurope28748 2831741 12960000000
AlgeriaAfrica2381741 37100000 188681000000
AndorraEurope46878115 3712000000
AngolaAfrica1246700 20609294 100990000000
...

name:國家名稱
continent:洲份
area:面積
population:人口
gdp:國內生產總值

示範

使用 SUM, Count, MAX, DISTINCT 和 ORDER BY.

Summary

展示世界的總人口。

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

列出所有的洲份, 每個只有一次。

 
SELECT DISTINCT(continent)
FROM world

找出非洲(Africa)的GDP總和。

 
SELECT SUM(gdp)
FROM world
WHERE continent = 'Africa'

有多少個國家具有至少百萬(1000000)的面積。

 
SELECT COUNT(name)
FROM world
WHERE area >= 1000000

('France','Germany','Spain')(“法國”,“德國”,“西班牙”)的總人口是多少?

 
SELECT SUM(population)
FROM world
WHERE name IN('France','Germany','Spain')

示範: 使用 GROUP BY 和 HAVING.

對於每一個洲份,顯示洲份和國家的數量。

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

對於每一個洲份,顯示洲份和至少有1000萬人(10,000,000)口國家的數目。

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

列出有至少100百萬(1億)(100,000,000)人口的洲份。

 
SELECT continent
FROM world
GROUP BY continent
HAVING SUM(population)>= 100000000
Clear your results

The nobel table can be used to practice more SUM and COUNT functions.

The next tutorial looks at the Table Tennis database. It shows how queries may use records from two related tables.