mysql-笔记 聚合函数

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

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

2 bit_and(expr) 返回按位与计算的结算 若是没有匹配的行 全部bits =1性能

bit_or(expr) 返回按位或计算的结算 若是没有匹配的行 全部bits=0code

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_nameci

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

对MyISAM表,若是从一个表中选择数据,没有其余的列字段,而且没有where条件,count(*) 返回很是快it

select count(*) from studentclass

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;

相关文章
相关标签/搜索