SQLZOO SUM and COUNT
1:展示世界的總人口。
SELECT SUM(population) FROM world;
2:列出所有的洲份, 每個只有一次。
SELECT DISTINCT continent FROM world;
3:找出非洲(Africa)的GDP總和。
SELECT SUM(gdp) FROM world WHERE continent = 'Africa';
4:有多少個國傢俱有至少百萬(1000000)的面積。
SELECT COUNT(name) FROM world WHERE area>=1000000;
5:('France','Germany','Spain')(“法國”,“德國”,“西班牙”)的總人口是多少?
SELECT SUM(population) FROM world WHERE name IN ('France','Germany','Spain');
6:For each continent show the continent and number of countries.
SELECT continent,COUNT(name) FROM world GROUP BY continent;
7:For each continent show the continent and number of countries with populations of at least 10 million.
SELECT continent , COUNT(name) FROM world WHERE population >=10000000 GROUP BY continent;
8:List the continents that have a total population of at least 100 million.
SELECT continent FROM world x
WHERE (SELECT SUM(population) FROM world y WHERE y.continent=x.continent)
GROUP BY continent
HAVING SUM(population)>=100000000;
總結
GROUP BY和HAVING功能
HAVING功能可以在GROUP BY排完的結果後進行篩選,如上面的第8例。