刷题网站SQLZoo,刷题语言MySQL
这套题目需要使用:SUM, Count, MAX, DISTINCT 和 ORDER BY.
SUM 函数返回数值列的总数(总额),语法是SELECT SUM(column_name) FROM table_name
COUNT() 函数返回匹配指定条件的行数(空值不计),语法为:SELECT COUNT(column_name) FROM table_name
MAX 函数返回一列中的最大值(NULL 值不包括在计算中),语法为:SELECT MAX(column_name) FROM table_name
关键词 DISTINCT 用于返回唯一不同的值,语法为SELECT DISTINCT 列名称 FROM 表名称
ORDER BY 语句用于根据指定的列对结果集进行排序,默认按照升序对记录进行排序,如果希望按照降序对记录进行排序,可以使用 DESC 关键字。语法是:SELECT column_name FROM table_name ORDER BY column_name
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。具体用法为:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value
World Country Profile: Aggregate functions
This tutorial is about aggregate functions such as COUNT, SUM and AVG. An aggregate function takes many values and delivers just one value. For example the function SUM would aggregate the values 2, 4 and 5 to deliver the single value 11.
name | continent | area | population | gdp |
---|---|---|---|---|
Afghanistan | Asia | 652230 | 25500100 | 20343000000 |
Albania | Europe | 28748 | 2831741 | 12960000000 |
Algeria | Africa | 2381741 | 37100000 | 188681000000 |
Andorra | Europe | 468 | 78115 | 3712000000 |
Angola | Africa | 1246700 | 20609294 | 100990000000 |
… | … | … | … | … |
Show the total population of the world.
world(name, continent, area, population, gdp)
SELECT SUM(population) FROM world
List all the continents - just once each.
select distinct continent from world
Give the total GDP of Africa
select sum(gdp) from world where continent = 'Africa'
How many countries have an area of at least 1000000
select count(name) from world where area > 1000000
What is the total population of (‘Estonia’, ‘Latvia’, ‘Lithuania’)
select sum(population) from world where name in ('Estonia', 'Latvia', 'Lithuania')
For each continent show the continent and number of countries.
select continent, count(name) from world group by continent
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
List the continents that have a total population of at least 100 million.
select continent from world group by continent having sum(population)>100000000