当前位置:网站首页>MySQL - database query - use of aggregate function, aggregate query, grouping query
MySQL - database query - use of aggregate function, aggregate query, grouping query
2022-07-04 20:53:00 【Sauerkraut】
Aggregate functions ( Statistical function )
SQL Allow calculation of data in the table , Take each column of data in the table as a whole , Do the longitudinal calculation .
column Indicates the field name , Perform some operations on a certain field
MAX、MIN、COUNT Null values are not calculated
COUNT(*) Returns the number of rows in all columns , Contains a null value
among COUNT Function can be used for any data type ( Because it only records the number of lines ), and SUM 、AVG Functions can only evaluate numeric types ,MAX and MIN Can be used for numerical 、 String or date time data type .
1. Count the number of employees in the enterprise
SELECT COUNT(*) FROM emp;
Be careful COUNT() Null values are not included
SELECT COUNT(mgr) FROM emp;
2. Count the average salary of employees in the enterprise
SELECT AVG(sal) FROM emp;
3. Query the maximum salary of employees in the enterprise
SELECT MAX(sal) FROM emp;
4. Query the minimum wage of employees in the enterprise
SELECT MIN(sal) FROM emp;
5. Calculate the sum of wages for all sales
SELECT sal FROM emp WHERE job='salesman';
SELECT SUM(sal) FROM emp WHERE job='salesman';
Group query
Aggregate functions are actually statistical functions .
Next, let's learn about grouping statistical query .
One thing to declare is that , Although statistical functions are generally combined with grouping queries , But there must be some cases of using it alone . for example : Basic paging operations when doing report display , Be sure to find out all the data .
So what is grouping ?
The concept of grouping is actually very common in life , For example, there are the following requirements :
1. In a class , Ask men and women to compete in a debate
2. In the company , Each department is required to compete in a tug of war
For the first demand , Suppose there is a student table , Then there must be a gender field in the student table , The gender can only be male or female .
And in the company , If you want to group departments , There must be duplication in the contents of a department column . Departments and employees have a one to many relationship , A Department corresponds to multiple employees .
Grouping is meaningful only for fields with duplicate data , We can check emp surface , Find the field positions that can be grouped job And department number deptno.
First, employee number empno It can't be repeated , If I repeat , It's the same person , full name ename Generally, there will be no repetition
grammar
GROUP BY Then write which field to group
HAVING Filter the grouped data after grouping
WHERE Filter the data before grouping
HAVING Filter the data after grouping
SELECT Grouping field / Aggregate functions FROM Table name [WHERE Conditions ] GROUP BY Grouping field [HAVING Conditions after grouping ];
Query requirement
1. Count the number of people in each job , Output all jobs , Then group it , Multiple repetitions are in a group , Finally, count the number of people in each group
SELECT job,COUNT(*) FROM emp GROUP BY job;
2. Count the minimum and maximum wages for each position
-- Count out each position
SELECT job FROM emp GROUP BY job;
SELECT job,MIN(sal),MAX(sal) FROM emp GROUP BY job;
The above two queries realize the basic operation of grouping , And these codes are written in standard format . But in the Group , Personally, I think the most troublesome thing is the restrictions of grouping operation .
matters needing attention
1. If a query ( non-existent GROUP BY
Clause ), So in SELECT
Only statistical functions are allowed in Clauses , No other fields are allowed .
When there is a statistical function , No other fields are allowed .
# Wrong statement
SELECT ename,COUNT(job) FROM emp;
# The right sentence
SELECT COUNT(job) FROM emp;
2. In statistical query ( There is GROUP BY
Clause ),SELECT
Only statistical functions and grouping fields are allowed in Clauses (GROUP BY
Fields defined later ), No other fields are allowed .
# Wrong statement
SELECT ename,COUNT(job) FROM emp GROUP BY job;
# The right sentence
SELECT deptno,COUNT(job) FROM emp GROUP BY job;
When grouping later , On one principle :GROUP BY
The allowed fields in the clause are SELECT
Allowed fields in Clause .
Query requirement
1. Display the salary of different positions less than 1500 The number of people
-- Show different positions
SELECT job FROM emp GROUP BY job;
-- Show the number of people in different positions
SELECT job,COUNT(*) FROM emp GROUP BY job;
-- Display the salary of different positions less than 1500 The number of people
SELECT job,COUNT(*) FROM emp WHERE sal<1500 GROUP BY job;
2. Add one more restriction , Only show the number of people greater than 2 Of , In fact, No 1 The result of the question will be screened again
SELECT job,COUNT(*) FROM emp WHERE sal<1500 GROUP BY job HAVING COUNT(*)>2;
3. Show non salespeople (salesman) The sum of the job name and the monthly salary of employees engaged in the same job , And the total monthly salary of employees engaged in the same work shall be greater than or equal to 5000
SELECT job FROM emp WHERE job!='salesman';
SELECT job,SUM(sal) FROM emp WHERE job!='salesman' GROUP BY job;
SELECT job,SUM(sal) AS total FROM emp WHERE job!='salesman' GROUP BY job HAVING total>=5000;
WHERE and HAVING difference
WHERE: Is to use... Before grouping ( There can be no GROUP BY), Statistical functions are not allowed .
HAVING: Is used after grouping ( Must be combined with GROUP BY), Statistical functions are allowed .
边栏推荐
- Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- LeetCode 871. 最低加油次数
- Four traversal methods of binary tree, as well as the creation of binary tree from middle order to post order, pre order to middle order, pre order to post order, and sequence [specially created for t
- Flet教程之 06 TextButton基础入门(教程含源码)
- Automatic generation of interface automatic test cases by actual operation
- What if the brightness of win11 is locked? Solution to win11 brightness locking
- word中插入圖片後,圖片上方有一空行,且删除後布局變亂
- So this is the BGP agreement
- How to adapt your games to different sizes of mobile screen
猜你喜欢
Aiming at the "amnesia" of deep learning, scientists proposed that based on similarity weighted interleaved learning, they can board PNAS
NetCore3.1 Json web token 中间件
测试员的算法面试题-找众数
Win11U盘拒绝访问怎么办?Win11U盘拒绝访问的有效解决方法
What if the WiFi of win11 system always drops? Solution of WiFi total drop in win11 system
一文搞懂Go语言中文件的读写与创建
电脑页面不能全屏怎么办?Win11页面不能全屏的解决方法
面对同样复杂的测试任务为什么大老很快能梳理解决方案,阿里十年测试工程师道出其中的技巧
How does win11 search for wireless displays? Win11 method of finding wireless display device
ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
随机推荐
[in-depth learning] review pytoch's 19 loss functions
分析伦敦银走势图的技巧
AP8022开关电源小家电ACDC芯片离线式开关电源IC
Implementation of redis distributed lock
Flet教程之 04 FilledTonalButton基础入门(教程含源码)
GVM use
浏览器渲染页面过程
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
idea插件
记一次重复造轮子(Obsidian 插件设置说明汉化)
记一次重复造轮子(Obsidian 插件设置说明汉化)
In operation (i.e. included in) usage of SSRs filter
What if the WiFi of win11 system always drops? Solution of WiFi total drop in win11 system
word中插入图片后,图片上方有一空行,且删除后布局变乱
How to solve the problem that win11 cannot write the value to the registry key?
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
NetCore3.1 Json web token 中间件
实操自动生成接口自动化测试用例
E-week finance | Q1 the number of active people in the insurance industry was 86.8867 million, and the licenses of 19 Payment institutions were cancelled
go语言笔记(2)go一些简单运用