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

边栏推荐
- MySQL uses the view to report an error, explain/show can not be issued; lacking privileges for underlying table
- It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
- 功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
- Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
- HR disgusted interview behavior
- The super fully automated test learning materials sorted out after a long talk with a Tencent eight year old test all night! (full of dry goods
- Anomalies seen during the interview
- Summary of common tools and technical points of PMP examination
- Long article review: entropy, free energy, symmetry and dynamics in the brain
- What insurance products should be bought for the elderly?
猜你喜欢

Network layer - routing

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

How to set the response description information when the response parameter in swagger is Boolean or integer

The super fully automated test learning materials sorted out after a long talk with a Tencent eight year old test all night! (full of dry goods

Function: find the approximate value of the limit of the ratio of the former term to the latter term of Fibonacci sequence. For example, when the error is 0.0001, the function value is 0.618056.

Function: write function fun to find s=1^k+2^k +3^k ++ The value of n^k, (the cumulative sum of the K power of 1 to the K power of n).
![[dynamic programming] leetcode 53: maximum subarray sum](/img/f0/80357f9ffc556f3ed4d3aa0901bb1d.jpg)
[dynamic programming] leetcode 53: maximum subarray sum

Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction

技术实践|线上故障分析及解决方法(上)
![[common error] UART cannot receive data error](/img/77/6ba56ce6e64beeb73a77d04af5bd0f.jpg)
[common error] UART cannot receive data error
随机推荐
手机异步发送短信验证码解决方案-Celery+redis
Day05 表格
The difference between objects and objects
From functional testing to automated testing, how did I successfully transform my salary to 15K +?
Pratique technique | analyse et solution des défaillances en ligne (Partie 1)
求esp32C3板子连接mssql方法
Release and visualization of related data
[cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
技術實踐|線上故障分析及解决方法(上)
HR disgusted interview behavior
@EnableAsync @Async
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
PMP 考试常见工具与技术点总结
Characteristics of ginger
Five high-frequency questions were selected from the 200 questions raised by 3000 test engineers
Introduction to unity shader essentials reading notes Chapter III unity shader Foundation
MySQL winter vacation self-study 2022 12 (2)
不得不会的Oracle数据库知识点(二)
(Introduction to database system | Wang Shan) Chapter V database integrity: Exercises