当前位置:网站首页>Use of aggregate functions
Use of aggregate functions
2022-07-03 19:35:00 【Piglet get】
Catalog
One 、 Aggregate function introduction
Ⅰ. How to realize the number of records in the calculation table ?
Ⅲ. Query the average bonus rate in the company
Use count(*),count(1),count( Specific fields ) Which is more efficient ?
demand 1: Query the average salary of each department , Maximum wage
demand 2: Check each one department_id,job_id The average wage of
2. practice : Query the highest salary ratio in each department 10000 High department information
Four 、SQL The underlying execution principle
( One )WHERE And HAVING Comparison of
2. If the filter condition has no aggregate function
( 3、 ... and )SQL Statement execution
One 、 Aggregate function introduction
1. Concept
Aggregate functions act on a set of data , And return a value for a set of data .
2. Type of aggregate function
①AVG and SUM function
Only applicable to fields of numeric type ( Or variable )
SELECT AVG(salary),SUM(salary),AVG(salary)*107
FROM employees;
# The following operations are meaningless
SELECT SUM(last_name),AVG(last_name),SUM(hire_date)
FROM employees;②MIN and MAX function
For numeric types 、 String type 、 Fields of date time type ( Or variable )
SELECT MAX(salary),MIN(salary),MAX(hire_date),MIN(hire_date)
FROM employees;
③COUNT function
Calculate the number of specified fields in the query structure
SELECT COUNT(employee_id),COUNT(salary),COUNT(2*salary),COUNT(1)
FROM employees;Ⅰ. How to realize the number of records in the calculation table ?
The way 1:COUNT(*)
The way 2:COUNT(1)
The way 3:COUNT( Specific fields ) —— Not necessarily right
Be careful : When calculating the number of occurrences of the specified field , It is not calculated NULL It's worth it
Ⅱ.AVG = SUM/COUNT
SELECT AVG(salary),SUM(salary)/COUNT(salary),
AVG(commission_pct),SUM(commission_pct)/COUNT(commission_pct),
SUM(commission_pct) / 107
FROM employees;

Ⅲ. Query the average bonus rate in the company
# Wrong writing
SELECT AVG(commission_pct)
FROM employees;
# Write it correctly
SELECT SUM(commission_pct) / COUNT(IFNULL(commission_pct,0)),
AVG(IFNULL(commission_pct,0))
FROM employees;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( Specific fields )
Two 、GROUP BY Use
demand 1: Query the average salary of each department , Maximum wage
SELECT AVG(salary)
FROM employees; # The average salary of the whole company
SELECT department_id,AVG(salary),MAX(salary)
FROM employees
GROUP BY department_id;
demand 2: Check each one department_id,job_id The average wage of
SELECT department_id,job_id,AVG(salary)
FROM employees
GROUP BY department_id,job_id;
Conclusion
1.SELECT Fields of non group functions appearing in , It must be stated that in GROUP BY in . conversely ,GROUP BY Fields declared in can not appear in SELECT in
2.GROUP BY The statement in FROM Back 、WHERE Back ,ORDER BY front 、LIMIT front
3. stay MySQL Use in WITH ROLLUP: Add a record after all the queried grouping records , This record Calculate the sum of all the records queried , That is, count the number of records .
3、 ... and 、HAVING Use
1. effect
Filtering data
2. practice : Query the highest salary ratio in each department 10000 High department information
# Wrong writing
SELECT department_id,MAX(salary)
FROM employees
WHERE MAX(salary) > 10000
GROUP BY department_id;
# Write it correctly
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000;
requirement
- If an aggregate function is used in the filter condition , Must be used HAVING To replace WHERE, Otherwise, an error will be reported
- HAVING It must be stated that in GROUP BY Behind
- In development , Use HAVING The premise is SQL Used in GROUP BY
Four 、SQL The underlying execution principle
When there is an aggregate function in the filter condition , Then this filter condition must be declared in HAVING in
When there is no aggregate function in the filter condition , Then this filter condition is declared in WHERE Medium or HAVING Either way , however , It is suggested that you declare in WHERE in
( One )WHERE And HAVING Comparison of
1. Scope of application
HAVING Has a wider scope of application
2. If the filter condition has no aggregate function
WHERE More efficient than HAVING

summary

( Two )SELECT sentence
1.SQL92 The grammar of
SELECT ......( There are aggregate functions )
FROM ......
WHERE Connection conditions of multiple tables AND Filter conditions that do not contain aggregate functions
GROUP BY ......
HAVING Filter conditions containing aggregate functions
ORDER BY ......(ASC / DESC)
LIMIT ......
2.SQL99 The grammar of
SELECT ......( There are aggregate functions )
FROM .... (LEFT / RIGHT) JOIN ... ON Connection conditions of multiple tables
(LEFT / RIGHT) JOIN ... ON ...
WHERE Filter conditions that do not contain aggregate functions
GROUP BY ......
HAVING Filter conditions containing aggregate functions
ORDER BY ......(ASC / DESC)
LIMIT ......
( 3、 ... and )SQL Statement execution

FROM ...... --> ON --> (LEFT / RIGHT JOIN) --> WHERE --> GROUP BY --> HAVING --> SELECT --> DISTINCT( duplicate removal ) --> ORDER BY( Sort ) --> LIMIT( Pagination display )
边栏推荐
- Chapter 2: 4-digit Kaplan number, search even digit Kaplan number, search n-digit 2-segment sum square number, m-digit ingenious square number without 0, specify the number to form a 7-digit square nu
- 05 -- QT OpenGL draw cube uniform
- [leetcode] [SQL] notes
- BOC protected alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC supplied by Qiyu
- Web Security (VII) specific process of authentication with session cookie scheme
- 03 -- QT OpenGL EBO draw triangle
- 第一章:求n的阶乘n!
- Zhang Fei hardware 90 day learning notes - personal record on day 5. Please see my personal profile / homepage for the complete record
- Octopus online ecological chain tour Atocha protocol received near grant worth $50000
- 2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
猜你喜欢

OSPF - detailed explanation of stub area and full stub area

BOC protected phenylalanine zinc porphyrin (Zn · TAPP Phe BOC) / iron porphyrin (Fe · TAPP Phe BOC) / nickel porphyrin (Ni · TAPP Phe BOC) / manganese porphyrin (Mn · TAPP Phe BOC) Qiyue Keke

Chapitre 1: le roi de shehan a mal calculé

The necessity of lean production and management in sheet metal industry

Xctf attack and defense world crypto advanced area best_ rsa

Streaming media server (16) -- figure out the difference between live broadcast and on-demand

2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)

Chapter 1: seek common? Decimal and S (D, n)

Think of new ways

第一章:求奇因数代数和,求同吗小数和s(d, n),简化同码小数和s(d, n),拓广同码小数和s(d, n)
随机推荐
Ego planner code parsing Bspline_ Optimizer section (2)
Kubernetes cluster builds efk log collection platform
第一章:简化同码小数和s(d, n)
Floating source code comment (38) parallel job processor
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
04 -- QT OpenGL two sets of shaders draw two triangles
Analyse du Code du planificateur ego bspline Section Optimizer (1)
I didn't cancel
The space of C disk is insufficient, and the computer becomes stuck. Quickly expand the capacity of C disk to make the system more smooth
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
第二章:基于分解的求水仙花数,基于组合的求水仙花数, 兰德尔数,求[x,y]内的守形数,探求n位守形数,递推探索n位逐位整除数
Chapter 1: find all factorial sums, Grand Prix site unified programming, three factorial sums, graphic point scanning, recursive factorial n of n!, Find the factorial n of n!, King Shehan miscalculate
UE source code analysis: uccharactermovementcomponent - rootmotion
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Recommend a GIF processing artifact less than 300K - gifsicle (free download)
Read the paper glodyne global topology preserving dynamic network embedding
[optics] vortex generation based on MATLAB [including Matlab source code 1927]
01. Preparation for automated office (free guidance, only three steps)
Chapter 1: seek common? Decimal and S (D, n)
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程