当前位置:网站首页>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
边栏推荐
- 2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)
- 1-Redis架构设计到使用场景-四种部署运行模式(上)
- 删除所有值为y的元素。数组元素中的值和y的值由主函数通过键盘输入。
- Oracle database knowledge points that cannot be learned (II)
- 查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
- 机器学习基础:用 Lasso 做特征选择
- Arc 135 supplementary report
- [error record] configure NDK header file path in Visual Studio
- Is it really possible that the monthly salary is 3K and the monthly salary is 15K?
- Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
猜你喜欢
Unity Shader入门精要读书笔记 第三章 Unity Shader基础
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
机器学习基础:用 Lasso 做特征选择
STM32 key light
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)
Interview script of Software Test Engineer
1-redis architecture design to use scenarios - four deployment and operation modes (Part 1)
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
(Introduction to database system | Wang Shan) Chapter V database integrity: Exercises
随机推荐
CLP information - how does the digital transformation of credit business change from star to finger?
7.1 学习内容
GUI application: socket network chat room
Msp32c3 board connection MSSQL method
机器学习基础:用 Lasso 做特征选择
Release and visualization of related data
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
What insurance products should be bought for the elderly?
Fundamentals of machine learning: feature selection with lasso
打印菱形图案
The FISCO bcos console calls the contract and reports an error does not exist
[error record] configure NDK header file path in Visual Studio
Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience
Is the account opening of Guoyuan securities really safe and reliable
Analysis and solution of lazyinitializationexception
Since the "epidemic", we have adhered to the "no closing" of data middle office services
STM32 key light
老姜的特点
Why use get/set instead of exposing properties