一、分组计算
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