第五关 SUM and COUNT
name(国家名) | continent(州份) | area(面积) | population(人口) | dgp(国民生产总值) |
---|
Afghanistan | Asia | 652230 | 25500100 | 20343000000 |
Albania | Europe | 28748 | 2831741 | 12960000000 |
Algeria | Africa | 2381741 | 37100000 | 188681000000 |
… | … | … | … | … |
5.1题目及答案
- 展示世界的總人口。
SELECT sum(population)
FROM world
- 列出所有的洲份, 每個只有一次。
select continent
from world group by continent
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')
- 對於每一個洲份,顯示洲份和國家的數量。
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
5.2总结
函数 | 用法说明 |
---|
sum | 求和,返回列的总和 |
max | 返回所选列的最大值 |
count | 返回符合指定条件的行数(NULL 不计入) |
distinct | 同 SELECT 一起使用,去除所有重复记录,只返回唯一项 |
group by | 以按一个或多个列对结果集进行分组,通常与集合函数(COUNT,MAX,MIN,SUM,AVG)一起使用 |
having | 对 GROUP BY 子句所产生的组施加条件,HAVING 子句必须紧随 GROUP BY 子句,并出现在 ORDER BY 子句(如果有的话)之前。 |
- having在select查询中的位置:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY