21. Aggregate functions in MySQL

 

Function name description
COUNT() Returns the number of parameter fields, not counting NULL records
SUM() Returns the sum of parameter fields
AVG() Returns the average value of the parameter field
MAX() Returns the maximum value of the parameter field
MIN () Returns the minimum value of the parameter field
GROUP_CONCAT() Return a connection string that matches the value of the parameter field
JSON_ARRAYAGG() Return the qualified parameter field values ​​as a single JSON array, new in MySQL5.7.22
JSON_OBJECTAGG() Return the qualified parameter field value as a single JSON object, new in MySQL5.7.22

COUNT (), SUM (), AVG (), MAX (), MIN () and GROUP_CONCAT () function can add DISTINCT in front of the parameters, which means that the relevant operations are not repeated records.

When the parameter of COUNT () is set to "*", it means that all records that meet the conditions (including NULL) are counted.

1. Prepare

 1 CREATE DATABASE mahaiwuji;
 2 USE mahaiwuji;
 3 CREATE TABLE goods (
 4     id INT,
 5     name VARCHAR (32),
 6     price INT
 7 ) ENGINE = INNODB DEFAULT CHARSET = utf8;
 8  9 INSERT INTO goods VALUES (1,'',10);
10 INSERT INTO goods VALUES (2,'键盘',11);
11 INSERT INTO goods VALUES (3,'鼠标',15);
12 INSERT INTO goods VALUES (4,'手机',20);
13 INSERT INTO goods VALUES (5,NULL,15);

2.COUNT()

. 1  the SELECT  COUNT (ID) the FROM Goods; - . 5 
2  . 3 the SELECT COUNT (name) the FROM Goods; - . 4, no statistical NULL . 4 . 5 the SELECT COUNT (. Price) the FROM Goods; - . 5 . 6 . 7 the SELECT COUNT ( the DISTINCT . price) the FROM Goods; - . 4, because there are two 15, the number is not repeated. 4 . 8 . 9 the SELECT COUNT ( * ) the FROM  
   
   
    goods; -- 5

3.SUM()

. 1  the SELECT  the SUM (. Price) the FROM Goods; - 71 is 
2  . 3 the SELECT the SUM ( the DISTINCT . Price) the FROM Goods; - 56 is, because there are two 15, only a forget  

4.AVG()

. 1  the SELECT  the AVG (. Price) the FROM Goods; - 14.2 
2  . 3 the SELECT the AVG ( the DISTINCT . Price) the FROM Goods; - 14, 15 because there are two, only a forget  

5.MAX()

1 SELECT MAX(price) FROM goods; -- 20
2 3 SELECT MAX(DISTINCT price) FROM goods; -- 20

6.MIN ()

1 SELECT MIN(price) FROM goods; -- 10
2 3 SELECT MIN(DISTINCT price) FROM goods; -- 10

7.GROUP_CONCAT()

1  - book, keyboard, mouse, mobile phone 
2  SELECT GROUP_CONCAT (name) FROM goods;

8.JSON_ARRAYAGG()

1  - ["Book", "Keyboard", "Mouse", "Mobile", null] 
2  SELECT JSON_ARRAYAGG (name) FROM goods;

9.JSON_OBJECTAGG()

1  - {"1": "Book", "2": "Keyboard", "3": "Mouse", "4": "Mobile Phone", "5": null} 
2  SELECT JSON_OBJECTAGG (id, name) the FROM Goods; 
 . 3  . 4 - error, since id is the name 5 is NULL, JSON the key can not be NULL . 5 the SELECT JSON_OBJECTAGG (name,. price) the FROM Goods; 
 

Guess you like

Origin www.cnblogs.com/mahaiwuji/p/12683632.html