SQL入门(二)

一、分组计算

1.创建分组(group by)

(1)使用 group by 关键词:select col1,count( * ) from table group by col1;
select countrycode from world.City group by countrycode ,返回 countrycode 的唯一值,相当于使用 distinct 关键词。在这里插入图片描述
select countrycode,avg(Population) as avg_pop from world.City group by countrycode 相当于按照 countrycode 中的每一组计算 population 的平均数。
在这里插入图片描述
(2)Group by 子句可以包含任意数量的列;即可以按照多个列分组。
在这里插入图片描述

注意:
(1)select 检索的列必须是 group by 的列,即检索的列会被 group by 的列限制。
(2)null 值将作为单独一组

2.过滤分组(having)

(1)使用 having 关键字,规定包含与排除哪些分组:select col1,count() from table group by col1
having count(
) > 10;
(2)与 where 的区别在于:where 作用于行,having 作用于组;where 在数据分组前过滤,having 在数
据分组后过滤(意味着 where 先执行,having 后执行)。where 过滤排除的行不在分组中。
在这里插入图片描述

3.分组与排序

使用 order by 可以对组进行排序:select col1,count() as num from table group by col1 having
count(
) > 10 order by num

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值