美文网首页
SQLZOO - SUM&COUNT笔记

SQLZOO - SUM&COUNT笔记

作者: adi0229 | 来源:发表于2020-03-25 17:17 被阅读0次

    依然是World 表格数据。

    知识点:SUM /COUNT/DISTINCT/MAX/GROUP BY/GROUP BY

    Aggregates

    SUM /COUNT/AVG/MAX/都属于“统计”(aggregates),每个方法可用于数值型属性,返回单行结果。与GROUP BY一起更有用。

    Distinct

    默认情况下, SELECT 查询会返回重复的数据行。我们可以通过DISTINCT关键词去重。

    ORDER BY

    ORDER BY指定排序方法,这里有两种常见的顺序ASC(从小到大) 和 DESC(从大到小)。

    语法基础示例:
    https://sqlzoo.net/wiki/Using_SUM,_Count,_MAX,_DISTINCT_and_ORDER_BY

    基础代码(适合纯新手):

    SELECT SUM(population), SUM(gdp)
      FROM bbc
      WHERE region = 'Europe'
    
    SELECT DISTINCT region FROM bbc
    
    SELECT name, population
      FROM bbc
      WHERE population > 100000000
      ORDER BY population DESC
    

    简易题目:
    https://sqlzoo.net/wiki/SUM_and_COUNT

    1.统计世界总人口

    SELECT SUM(population)
    FROM world
    

    2.列出所有大洲(每个大洲只出现一次)

    SELECT DISTINCT(continent)
    FROM world
    

    3.统计世界总人口

    SELECT SUM(population)
    FROM world
    

    4.列出所有大洲(每个大洲只出现一次)

    SELECT DISTINCT(continent)
    FROM world
    

    GROUP BY子句的简易示例

    https://sqlzoo.net/wiki/Using_GROUP_BY_and_HAVING.

    GROUP BY &HAVING

    GROUP BY continent, 每一个大洲的值只会返回一次,其他列的数据是对应的 SUM 数值总计或者 COUNT频次统计。

    HAVING可以过滤 GROUP BY 后的数据

    基础代码(适合纯新手):

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

    5.统计三个国家的总人口

    SELECT SUM(population)
    FROM world
    WHERE name IN  ('Estonia', 'Latvia', 'Lithuania')
    

    6.列出 每个大洲的国家数量

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

    7.列出每个大洲中人口总数超过 1000 万的国家

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

    8.列出人口总数超过 1亿的大洲

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

    相关文章

      网友评论

          本文标题:SQLZOO - SUM&COUNT笔记

          本文链接:https://www.haomeiwen.com/subject/bpdmlctx.html