当前位置:网站首页>MySQL - use of aggregate functions and group by groups
MySQL - use of aggregate functions and group by groups
2022-07-04 00:59:00 【Wan Li Gu Cheng】
List of articles
MySQL—— Aggregate functions and group by The use of groups
1、 Aggregate function introduction
SQL The aggregate function calculates a set of data and returns a single value .
except COUNT outside , The aggregate function ignores null values , If COUNT The application object of the function is a certain column name , And the column has a null value , here COUNT Null values are still ignored .
Because the aggregate function operates on a set of values , So it usually works with SELECT Of the statement GROUP BY Clauses are used together , To calculate the metrics that provide information for each group .
2、GROUP BY grouping
Grouping is one of the most important tasks that must be handled when using a database . To group rows , Use GROUP BY Clause .
GROUP BY Clause is SELECT Optional clause of the statement , It groups rows based on matching values in the specified column , Each group returns to a row .
GROUP BY Syntax of clause :
SELECT
column1,
column2,
GROUP_FUNCTION (column3)
FROM
table1
WHERE
a = b
GROUP BY
column1,
column2
HAVING
c = d
ORDER BY
column2 DESC;
stay SELECT The inclusion of aggregate functions in clauses is not mandatory . however , If you use aggregate functions , It will calculate the sum of each group .
It's important to note that , Apply before grouping rows WHERE Clause , After grouping the rows, apply HAVING Clause . let me put it another way ,WHERE Clause applies to the row , and HAVING Clause applies to grouping .
To sort groups , Please be there. GROUP BY Clause followed by ORDER BY Clause .
GROUP BY The columns appearing in the clause are called grouping columns . If the grouping column contains NULL value , Then all NULL The values are summarized into a group , because GROUP BY The clause says NULL The values are equal .
3、 Common aggregate functions
| The name of the function | effect |
|---|---|
| MAX | Query the maximum value of the specified column |
| MIN | Query the minimum value of the specified column |
| COUNT | Count the number of rows in the query result |
| SUM | Sum up , Returns the sum of the specified columns |
| AVG | averaging , Returns the average of the specified column data |
AVG/ SUM Only applicable to fields of numeric type ( Or variable )
MAX / MIN For numeric types 、 String type 、 Fields of date time type ( Or variable )
Use COUNT(*)、COUNT(1)、COUNT( Specific fields ) Which is more efficient :
If you are using MyISAM Storage engine , Then the efficiency of the three is the same , All are O(1)
If you are using InnoDB Storage engine , Then the efficiency of the three COUNT(*) = COUNT(1) >COUNT( Field )
Using examples
-- AVG Calculate the average wage per department
SELECT e.department_id,department_name, ROUND(AVG(salary), 0) avg_salary
FROM employees e
JOIN departments d on e.department_id = d.department_id
GROUP BY department_name
ORDER BY department_name;
-- SUM Return the total salary of all employees in each department
SELECT department_id, SUM(salary)
FROM employees
GROUP BY department_id;
-- MAX / MIN Return the minimum and maximum salary of employees in each department
SELECT department_name, MIN(salary) min_salary,MAX(salary) max_salary
FROM employees e
JOIN departments d on e.department_id = d.department_id
GROUP BY department_name
ORDER BY department_name;
-- COUNT Return the number of people in each department in ascending order according to the Department name
SELECT department_name, COUNT(*) headcount
FROM employees e
JOIN departments d on e.department_id = d.department_id
GROUP BY department_name
ORDER BY department_name;
-- Query minimum salary greater than 6000 Information of various departments 、 Maximum salary and average salary
select e.department_id,department_name,min(salary) min_salary,max(salary) max_salary,round(avg(salary),2) average_salary
from employees e
join departments d on e.department_id = d.department_id
GROUP BY e.department_id
having min_salary > 6000
order by department_id ;
-- The number of searchers is greater than 5 The department in charge of the
SELECT e.department_id,department_name,COUNT(employee_id) headcount
FROM employees e
JOIN departments d ON d.department_id = e.department_id
GROUP BY e.department_id
HAVING headcount > 5
ORDER BY headcount DESC;
#1.where Clause can be filtered using group functions ?
-- Can not be
#2. Query the maximum salary of employees in the company , minimum value , Average , The sum of the
select max(salary),min(salary),avg(salary),sum(salary) from employees;
#3. Query each job_id It's the maximum wage of employees , minimum value , Average , The sum of the
select job_id, max(salary),min(salary),avg(salary),sum(salary)
from employees
group by job_id;
#4. Select each job_id Number of employees
select job_id,count(*)
from employees
group by job_id;
#5. Find out the difference between the maximum wage and the minimum wage (DIFFERENCE)
select max(salary) - min(salary) DIFFERENCE
from employees;
#6. Check the minimum wage of employees under each manager , The minimum wage should not be lower than 6000, Employees without managers are not counted
select emp.employee_id,emp.manager_id, min(emp.salary) min_salary
from employees emp
join employees mang
on emp.manager_id = mang.employee_id
group by emp.manager_id
having min_salary >= 6000;
-- or
select employee_id,manager_id, min(salary) min_salary
from employees
where manager_id is not null
group by manager_id
having min_salary >= 6000;
#7. Query the names of all departments ,location_id, Number of employees and average salary , And in descending order of average wage
select department_name,location_id,count(employee_id),round(avg(salary),2) avg_salary
from departments d
left join employees e on e.department_id = d.department_id
group by department_name
order by avg_salary desc;
#8. Query each type of work 、 The name of each department 、 The name of the type of work and the minimum wage
select department_name,job_id,min(salary)
from employees e
right join departments d on e.department_id = d.department_id
group by job_id, d.department_id;
4、SQL Execution order
SELECT The complete structure of the statement (SQL99)
select duplicate removal Fields to query from surface ( Be careful : Tables and fields can be aliased )
xxxx join Table to connect on Equivalent judgment ( The order : First on Again where)
where ( Specific value / Subquery , Filter conditions that do not contain aggregate functions )
group by( Group by that sub segment )
having ( Filter the grouped information , Conditions and where equally , Different location , Filter conditions containing aggregate functions )
order by( By which field )
limit ( Pagination )
SQL The order in which statements are executed

边栏推荐
- [complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
- 功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
- 7.1 学习内容
- Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
- Function: find the sum of the elements on the main and sub diagonal of the matrix with 5 rows and 5 columns. Note that the elements where the two diagonals intersect are added only once. For example,
- [cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
- Sequence list and linked list
- The FISCO bcos console calls the contract and reports an error does not exist
- [software testing] you haven't mastered these real interview questions of big companies?
- Generic
猜你喜欢

基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能

老姜的特点

中电资讯-信贷业务数字化转型如何从星空到指尖?

Who moved my code!

Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience

Introduction to A-frame virtual reality development

1-Redis架构设计到使用场景-四种部署运行模式(上)

Sorry, Tencent I also refused

It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction

AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用
随机推荐
Sequence list and linked list
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
Struct in linked list
Why use get/set instead of exposing properties
CesiumJS 2022^ 源码解读[8] - 资源封装与多线程
The difference between fetchtype lazy and eagle in JPA
Interview script of Software Test Engineer
What insurance products should be bought for the elderly?
The first training of wechat applet
STM32 key light
不得不会的Oracle数据库知识点(一)
What is the potential of pocket network, which is favored by well-known investors?
On covariance of array and wildcard of generic type
Severity code description the project file line prohibits the display of status error c4996 fopen ('fscanf ', StrCmp): this function or variable may be unsafe The most comprehensive solution
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
Msp32c3 board connection MSSQL method
Since the "epidemic", we have adhered to the "no closing" of data middle office services
Pair
Is the securities account opened by Caicai for individuals safe? Is there a routine