前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >sqlzoo练习17-group by and having

sqlzoo练习17-group by and having

作者头像
皮大大
发布2021-03-02 15:00:22
2780
发布2021-03-02 15:00:22
举报
文章被收录于专栏:机器学习/数据可视化

GROUP BYandHAVING By including a GROUP BY clause functions such as SUM and COUNT are applied to groups of items sharing values. When you specify GROUP BY continent the result is that you get only one row for each different value of continent. All the other columns must be “aggregated” by one of SUM, COUNT … The HAVING clause allows use to filter the groups which are displayed. The WHERE clause filters rows before the aggregation, the HAVING clause filters after the aggregation.

  • where 过滤在前
  • group by 中间
  • having 过滤在后
代码语言:javascript
复制
-- 1
SELECT continent, COUNT(name) 
FROM world
GROUP BY continent

-- 2
SELECT continent, SUM(population)
FROM world
GROUP BY continent

-- 3
/*WHERE and GROUP BY. The WHERE filter takes place before the aggregating function. For each relevant continent show the number of countries that has a population of at least 200000000.*/
select continent, count(name)
from world 
where population > 200000000
group by continent;

-- 4
/*GROUP BY and HAVING. The HAVING clause is tested after the GROUP BY. You can test the aggregated values with a HAVING clause. Show the total population of those continents with a total population of at least half a billion.*/
SELECT continent, SUM(population)
FROM world
GROUP BY continent               
HAVING SUM(population) > 500000000   -- 分组之后再把大于50000000的筛选出来

-- 5
/*For each continent show the continent and number of countries.*/
select continent, count(name)   -- 分清sum 和 count的关系
from world
group by continent;

-- 6
/*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

-- 7
/*List the continents that have a total population of at least 100 million.*/
select continent
from world 
group by continent
having sum(population) >= 100000000;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-9,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档