mysql-笔记 聚合函数

1 avg([distinct] expr) 返回expr的平均值 distinct:去除重复值。如果没有匹配的行返回null

select student_name,avg(test_score) from student group by student_name;

2 bit_and(expr) 返回按位与计算的结算 如果没有匹配的行 所有bits =1

bit_or(expr) 返回按位或计算的结算 如果没有匹配的行 所有bits=0

bit_xor(expr)返回按异或计算的结算 如果没有匹配的行所有bits=0

3 count(expr) 返回select 行中非null的expr计数值。结果是bigint值,如果没有匹配的行,则返回0

select student.student_name,count(1) from student,course where student.student_id=course.student_id group by student_name

inndb 使用相同的方式 处理count(*)与count(1) ,没有性能上的不同

对MyISAM表,如果从一个表中选择数据,没有其他的列字段,并且没有where条件,count(*) 返回非常快

select count(*) from student

4 count(distinct expr,[expr...]) 返回不同非null值的记录数,如果没有匹配的行,返回0

select count(distinct results) from student; 可以得到一组非null值的字段值的数量

 5 Group_concat( [distinct] expr[,expr...] order by {unsigned_integer | col_name | expr} [asc|desc][,col_name...]][separator str_val])

按一列分组,将 expr 对应的所有 值 打印在一行上,可以按 expr排序 ,每个值之间可以用 ‘ ’ 或其他 符号分隔

列的长度受:group_concat_max_len 系统参数的影响,可以设置大一些但是也要受到max_allowed_packet的值的影响

select student_name ,group_concat(distinct test_score order by test_score desc separator ' ')

from student

group by student_name;

6 json_arrayagg(col_or_expr) 返回包含分组的行的一组json 数组 

select partcode,json_arrayagg(partname) from tbinfopart group partcode;

7 json_objectagg(key,value) 接收2列或2个表达式参数,第一个做为 key,第二个做为值。返回一个对象包含 key-value值,如果有重复键取最后一个

select partcode,json_objectagg(partname,specialtype) from tbinfopart group by partcode;

8 max([distinct] expr) 返回最大值,可以是字符串。有没有distinct 结果一样。如果没有取到行,返回null

min([distinct] expr)返回最小值,可以是字符串。enum/set字段按字符值做比较,不按他的位置。与orderby相返。

9 sum([distinct] expr) 返回求合值,如果没有行则返回null 

10 group by XXX with rollup 在分类汇总的数据上再按每一个分类汇总一个合计行

select year,country,product,sum(profit) as profit from sales group by year,country,product with rollup;

group by XXX with rollup limit Y 取分类汇总的Y行

any_value():显示不在分类里的列

select partcode,any_value(partname),sum(id) from tbinfopart group by partcode with rollup;

原文地址:https://www.cnblogs.com/caojuansh/p/10951214.html