当前位置:网站首页>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

边栏推荐
- 基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
- 【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client
- The culprit of unrestrained consumption -- Summary
- 功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
- Future源码一观-JUC系列
- Print diamond pattern
- Technical practice online fault analysis and solutions (Part 1)
- The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
- 查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
- A malware detection method for checking PLC system using satisfiability modulus theoretical model
猜你喜欢

Att & CK actual combat series - red team actual combat - V

AI helps make new breakthroughs in art design plagiarism retrieval! Professor Liu Fang's team paper was employed by ACM mm, a multimedia top-level conference

功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。

1-redis architecture design to use scenarios - four deployment and operation modes (Part 1)

Unity Shader入门精要读书笔记 第三章 Unity Shader基础

A-Frame虚拟现实开发入门

Sorry, Tencent I also refused

Weekly open source project recommendation plan
![[dynamic programming] leetcode 53: maximum subarray sum](/img/f0/80357f9ffc556f3ed4d3aa0901bb1d.jpg)
[dynamic programming] leetcode 53: maximum subarray sum

Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
随机推荐
From functools import reduce -- see the use of reduce function from typical examples
Is it really possible that the monthly salary is 3K and the monthly salary is 15K?
How to be a professional software testing engineer? Listen to the byte five year old test
不得不会的Oracle数据库知识点(一)
OS interrupt mechanism and interrupt handler
AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用
手机异步发送短信验证码解决方案-Celery+redis
On covariance of array and wildcard of generic type
swagger中响应参数为Boolean或是integer如何设置响应描述信息
A malware detection method for checking PLC system using satisfiability modulus theoretical model
中电资讯-信贷业务数字化转型如何从星空到指尖?
All in one 1412: binary classification
Is the account opening of Guoyuan securities really safe and reliable
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
Mobile asynchronous sending SMS verification code solution -efficiency+redis
Why use get/set instead of exposing properties
A-Frame虚拟现实开发入门
Pair
The culprit of unrestrained consumption -- Summary
Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing