当前位置:网站首页>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
边栏推荐
- Flutter local database sqflite
- be based on. NETCORE development blog project starblog - (14) realize theme switching function
- Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience
- 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
- What insurance products should be bought for the elderly?
- 【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client
- 不得不会的Oracle数据库知识点(一)
- Att & CK actual combat series - red team actual combat - V
- Unity Shader入门精要读书笔记 第三章 Unity Shader基础
- How to be a professional software testing engineer? Listen to the byte five year old test
猜你喜欢
Analysis and solution of lazyinitializationexception
老姜的特点
Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience
【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client
[error record] configure NDK header file path in Visual Studio (three header file paths of NDK | ASM header file path selection related to CPU architecture)
Is it really possible that the monthly salary is 3K and the monthly salary is 15K?
Makefile judge custom variables
功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
Data mining vs Machine Learning: what is the difference between them? Which is more suitable for you to learn
Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
随机推荐
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
[common error] UART cannot receive data error
不得不会的Oracle数据库知识点(四)
[common error] custom IP instantiation error
How to set the response description information when the response parameter in swagger is Boolean or integer
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
swagger中响应参数为Boolean或是integer如何设置响应描述信息
PMP 考试常见工具与技术点总结
MPLS experiment
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
Regular expression of shell script value
Arc 135 supplementary report
Technical practice online fault analysis and solutions (Part 1)
Flutter local database sqflite
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
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
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
Who moved my code!
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)
挖财帮个人开的证券账户安全吗?是不是有套路