当前位置:网站首页>Tutorial on principles and applications of database system (045) -- MySQL query (VII): aggregate function
Tutorial on principles and applications of database system (045) -- MySQL query (VII): aggregate function
2022-07-24 00:49:00 【Rsda DBA_ WGX】
Database system principle and Application Tutorial (045)—— MySQL Inquire about ( 7、 ... and ): Aggregate functions
Aggregate function is also called statistical function , You can count and summarize the query results , Calculate the data value of a column in the table and return a single value . Aggregate functions are often associated with GROUP BY Clauses are used together .
Common aggregation functions include SUM、COUNT、AVG、MAX and MIN, Realize the statistics of data in the table ( Sum up 、 Count 、 Average 、 Maximum and minimum values, etc ).GROUP_CONCAT Functions are similar to aggregate functions , You can connect the data values in a column .
One 、 Usage of aggregate function
The syntax format of the aggregate function is as follows :
-- 1、 Counting function
-- Use count(*) Do not ignore when NULL value , Use count( Name | expression ) Ignore NULL value
COUNT(distinct *| Name | expression )
-- 2、 Sum function
-- The type of the column or the type of the return value of the expression must be a numeric type
SUM( Name | expression )
-- 3、 Find the average function
-- The type of the column or the type of the return value of the expression must be a numeric type
AVG( Name | expression )
-- 4、 Find the maximum function
-- The type of the column or the type of the return value of the expression can be any type
MAX( Name | expression )
-- 5、 Find the minimum function
-- The type of the column or the type of the return value of the expression can be any type
MIN( Name | expression )
-- 6、 Connect data value functions
-- The type of the column or the type of the return value of the expression can be any type
-- Use separator Specify the separator between data , If omitted separator, The default separator is comma
-- Use distinct Can remove duplicate data
GROUP_CONCAT([distinct] Name [order by Sort field asc|desc] separator ' Separator ')
explain :
(1) If the aggregate function is used in the query , Without grouping , The query result has only one row ( There is only one statistical result ). If you use GROUP BY grouping , Then each group has a statistical result .
(2) If the aggregate function is used in the query , Without grouping ,SELECT In addition to the aggregate function , Generally, there should be no column name .
for example :
mysql> select s_name,count(*) from student;
ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'mydb.student.s_name'; this is incompatible with sql_mo
de=only_full_group_by
mysql> select count(*) from student;
+----------+
| count(*) |
+----------+
| 14 |
+----------+
1 row in set (0.00 sec)
Two 、 Counting function :COUNT
Use COUNT( ) Function is used to count the number of records , Usually with GROUP BY Clause pooling .
The syntax is as follows :
-- Use count(*) Do not ignore when NULL value , Use count( Field | expression ) Ignore NULL value
COUNT(distinct *| Name | expression )
for example :
(1) Count all the students
mysql> select count(*) from student;
+----------+
| count(*) |
+----------+
| 14 |
+----------+
1 row in set (0.00 sec)
(2) The statistical address is 【 Xinxiang City 】 The number of students
mysql> select count(1) from student where addr = ' Xinxiang City ';
+----------+
| count(1) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
(3) Statistics 2000 The number of students born after
mysql> select count(*) from student where birth >= '2000-1-1';
+----------+
| count(*) |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)
(4) Count the number of addresses where students are
mysql> select count(distinct addr) from student;
+----------------------+
| count(distinct addr) |
+----------------------+
| 4 |
+----------------------+
1 row in set (0.01 sec)
(5) Data exists NULL Situation of value
mysql> create table t12(id int primary key,name char(20),salary int);
Query OK, 0 rows affected (0.00 sec)
mysql> insert into t12
-> values(1,'Jack',5200),(2,'Tom',4800),(3,'Black',3700),(4,null,null),(5,null,null);
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0
-- Count the number of records
mysql> select count(*) from t12;
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set (0.00 sec)
-- Count the number of records ( Ignore name by NULL The record of )
mysql> select count(name) from t12;
+-------------+
| count(name) |
+-------------+
| 3 |
+-------------+
1 row in set (0.00 sec)
3、 ... and 、 Sum function :SUM
Use SUM( ) Function can sum the data of a column in the table , Ignore in Statistics NULL value . If there is no matching line , Then return to NULL value . Often with GROUP BY Clause pooling .
The syntax is as follows :
-- The type of the column or the type of the return value of the expression must be a numeric type
SUM( Field | expression )
for example :
(1) Statistics students S2011 Total score of elective courses .
mysql> select sum(score) from score where s_id = 'S2011';
+------------+
| sum(score) |
+------------+
| 318 |
+------------+
1 row in set (0.04 sec)
(2) Statistics t12 In the table salary The sum of the columns .
mysql> select * from t12;
+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Jack | 5200 |
| 2 | Tom | 4800 |
| 3 | Black | 3700 |
| 4 | NULL | NULL |
| 5 | NULL | NULL |
+----+-------+--------+
5 rows in set (0.00 sec)
-- Ignore in Statistics NULL value
mysql> select sum(salary) from t12;
+-------------+
| sum(salary) |
+-------------+
| 13700 |
+-------------+
1 row in set (0.00 sec)
(3) Statistics 2000 Number of students born after .
mysql> select sum(1) from student where birth >= '2000-1-1';
+--------+
| sum(1) |
+--------+
| 4 |
+--------+
1 row in set (0.00 sec)
(4) The statistical address is 【 Xinxiang City 】 The number of students .
mysql> select sum(if(addr = ' Xinxiang City ',1,0)) cnt from student;
+------+
| cnt |
+------+
| 2 |
+------+
1 row in set (0.01 sec)
Four 、 Find the average function :AVG
Use AVG( ) Function can calculate the average value of a column of data in the table . Ignore in Statistics NULL value . Often with GROUP BY Clause pooling .
The syntax is as follows :
-- The type of the column or the type of the return value of the expression must be a numeric type
AVG( Field | expression )
for example :
(1) Statistics students S2011 Average score of elective courses .
mysql> select avg(score) from score where s_id = 'S2011';
+------------+
| avg(score) |
+------------+
| 79.5000 |
+------------+
1 row in set (0.00 sec)
(2) Statistics t12 In the table salary The average of the columns .
mysql> select * from t12;
+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Jack | 5200 |
| 2 | Tom | 4800 |
| 3 | Black | 3700 |
| 4 | NULL | NULL |
| 5 | NULL | NULL |
+----+-------+--------+
5 rows in set (0.00 sec)
-- Ignore in Statistics NULL value
mysql> select avg(salary) from t12;
+-------------+
| avg(salary) |
+-------------+
| 4566.6667 |
+-------------+
1 row in set (0.00 sec)
(3) Ask the average age of all students .
-- Average value of statistical expression
mysql> select avg(year(now())-year(birth)) avg_age from student;
+---------+
| avg_age |
+---------+
| 22.9286 |
+---------+
1 row in set (0.00 sec)
5、 ... and 、 Find the maximum function :MAX
Use MAX( ) Function counts the maximum value of a column of data . Ignore in Statistics NULL value . Often with GROUP BY Clause pooling .
The syntax is as follows :
-- The type of the column or the type of the return value of the expression can be any type
MAX( Field | expression )
for example :
(1) Inquire about C102 The highest score of the course .
mysql> select max(score) from score where c_id = 'C102';
+------------+
| max(score) |
+------------+
| 97 |
+------------+
1 row in set (0.00 sec)
(2) Query the maximum age of all students .
mysql> select max(year(now())-year(birth)) max_age from student;
+---------+
| max_age |
+---------+
| 24 |
+---------+
1 row in set (0.00 sec)
6、 ... and 、 Find the minimum function :MIN
Use MIN( ) Function counts the minimum value of a column of data . Ignore in Statistics NULL value . Often with GROUP BY Clause pooling .
The syntax is as follows :
-- The type of the column or the type of the return value of the expression can be any type
MIN( Field | expression )
for example :
(1) Inquire about C102 Minimum score of the course .
mysql> select min(score) from score where c_id = 'C102';
+------------+
| min(score) |
+------------+
| 52 |
+------------+
1 row in set (0.00 sec)
(2) Query the minimum age of all students .
mysql> select min(year(now())-year(birth)) min_age from student;
+---------+
| min_age |
+---------+
| 22 |
+---------+
1 row in set (0.00 sec)
7、 ... and 、 Connect data value functions :GROUP_CONCAT
Use GROUP_CONCAT( ) Function can connect the data values of a column into a string , The data values are separated by the specified separator ( Default to comma ).
The syntax is as follows :
-- The type of the column or the type of the return value of the expression can be any type
-- Use separator Specify the separator between data , If omitted separator, The default separator is comma
-- Use distinct Can remove duplicate data
GROUP_CONCAT([distinct] Name [order by Sort field asc|desc] separator ' Separator ');
for example :
(1) The inquiry address is 【 Zhengzhou city 】 List of students , Names are separated by commas .
mysql> select group_concat(s_name) from student where addr = ' Zhengzhou city ';
+----------------------------------------------------------+
| group_concat(s_name) |
+----------------------------------------------------------+
| Cao mengde , Liu Yan , Zhou Huajian , Zhang Xueyou , Lee Myung Bak , Vinci |
+----------------------------------------------------------+
1 row in set (0.00 sec)
(2) The inquiry address is 【 Zhengzhou city 】 List of students , Use 【||】 Separate .
mysql> select group_concat(s_name separator '||') from student where addr = ' Zhengzhou city ';
+---------------------------------------------------------------+
| group_concat(s_name separator '||') |
+---------------------------------------------------------------+
| Cao mengde || Liu Yan || Zhou Huajian || Zhang Xueyou || Lee Myung Bak || Vinci |
+---------------------------------------------------------------+
1 row in set (0.00 sec)
(3) The inquiry address is 【 Zhengzhou city 】 List of students , Use 【|】 Separate , And press birth Sort .
mysql> select s_name,birth,addr from student where addr = ' Zhengzhou city ' order by birth;
+-----------+---------------------+-----------+
| s_name | birth | addr |
+-----------+---------------------+-----------+
| Cao mengde | 1998-02-13 00:00:00 | Zhengzhou city |
| Liu Yan | 1998-06-24 00:00:00 | Zhengzhou city |
| Zhang Xueyou | 1998-07-06 00:00:00 | Zhengzhou city |
| Zhou Huajian | 1999-05-25 00:00:00 | Zhengzhou city |
| Lee Myung Bak | 1999-10-26 00:00:00 | Zhengzhou city |
| Vinci | 1999-12-31 00:00:00 | Zhengzhou city |
+-----------+---------------------+-----------+
6 rows in set (0.00 sec)
mysql> select group_concat(s_name order by birth separator '|') from student where addr = ' Zhengzhou city ';
+----------------------------------------------------------+
| group_concat(s_name order by birth separator '|') |
+----------------------------------------------------------+
| Cao mengde | Liu Yan | Zhang Xueyou | Zhou Huajian | Lee Myung Bak | Vinci |
+----------------------------------------------------------+
1 row in set (0.00 sec)
(4) Look up all the students addr list .
mysql> select group_concat(addr) from student;
+---------------------------------------------------------------------------------------------+
| group_concat(addr) |
+---------------------------------------------------------------------------------------------+
| Xinyang City , Xinxiang City , Zhengzhou city , Zhengzhou city , Xinyang City , Kaifeng City , Kaifeng City , Zhengzhou city , Xinxiang City , Xinyang City , Kaifeng City , Zhengzhou city , Zhengzhou city , Zhengzhou city |
+---------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
-- Eliminate duplicate addresses
mysql> select group_concat(distinct addr) from student;
+-----------------------------------------+
| group_concat(distinct addr) |
+-----------------------------------------+
| Xinyang City , Kaifeng City , Xinxiang City , Zhengzhou city |
+-----------------------------------------+
1 row in set (0.00 sec)
边栏推荐
- Redis common commands
- How can dbcontext support the migration of different databases in efcore advanced SaaS system
- [video game training] non contact object size and shape measurement 2020 video game G
- SAP 实施项目中涉及到编程方式操作 Excel 的几种场景介绍
- 工作3年的测试员跳槽后工资是原来的2倍,秘诀原来是......
- Redis data structure
- 采坑websocket总结
- Overview of data model design method
- [data mining engineer - written examination] Haier company in 2022
- Are the top ten securities companies risky and safe to open accounts?
猜你喜欢

English grammar_ Demonstrative pronoun -such / the same

Development of main applet for business card traffic near the map

Creo 9.0 mouse button operation for model observation

Database connection pool & dbutils

This is a big problem

Redis common commands

MySQL's heart index

Flutter | the easiest way to add header and footer to listview

Classic examples of C language - adding two scores

XXL job realizes the code parsing of email sending warnings (line by line code interpretation)
随机推荐
采坑websocket总结
PostgreSQL snapshot optimization globalvis new system analysis (greatly enhanced performance)
Classic example of C language - commodity inspection code
Distributed cap principle
Coloring old photos - deoldify get started quickly
Classic example of C language - print the input two digits in reverse order
Installation and use of appscan
Blockbuster | certik: Web3.0 industry safety report release in the second quarter of 2022 (PDF download link attached)
QT入门篇(2.1初入QT的开始第一个程序)
How can dbcontext support the migration of different databases in efcore advanced SaaS system
Image processing 1:rgb888_ YCbCr444
【LeetCode第 83 场双周赛】
Overview of data model design method
High number_ Chapter 2 differential calculus of multivariate functions__ Geometric application of partial derivatives_ Tangent and normal plane of space curve
通信模块整理(二)HC-05
Small farmers also have big goals in the test, and the latest big bat interview summary (constantly updating...)
How to speed up matrix multiplication -- optimizing GEMM (CPU single thread)
MySQL table field quantity limit and row size limit
How to use mitmproxy to get data return in automated testing?
Detailed overview of data standards -2022