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;

相關文章
相關標籤/搜索