当前位置:网站首页>100 important knowledge points that SQL must master: summary data
100 important knowledge points that SQL must master: summary data
2022-06-30 11:02:00 【Guge academic】
9.1 Aggregation function
We often need to aggregate data without actually retrieving it , So SQL Provides a dedicated
Functions of doors . Use these functions ,SQL Queries can be used to retrieve data , For analysis and reporting
Generate . Examples of this type of retrieval are :
Determine the number of rows in the table ( Or the number of rows that satisfy a condition or contain a specific value );
Get the sum of some rows in the table ;
Find table columns ( Or all or some particular line ) The maximum of 、 minimum value 、 Average .
All the above examples need to summarize the data in the table , Without having to find out the data itself . therefore , return
Returning the actual table data is a waste of time and processing resources ( Not to mention bandwidth ). Say it again ,
What we really want is to summarize information .
To facilitate this type of Retrieval ,SQL given 5 Aggregate functions , See table 9-1. These functions
Can carry out the above search . Different from the data processing functions introduced in the previous chapter ,SQL The aggregation function of
In all kinds of major SQL There is quite consistent support in the implementation .
Aggregation function (aggregate function)
Functions that run on certain lines , Calculates and returns a value .
surface 9-1 SQL Aggregation function
Letter Count say bright
AVG() Returns the average of a column
COUNT() Returns the number of rows in a column
MAX() Returns the maximum value of a column
MIN() Returns the minimum value of a column
SUM() Returns the sum of values in a column
The following describes the use of each function .
9.1.1 AVG() function
AVG() By counting the number of rows in the table and calculating the sum of their column values , Find the average value of this column . AVG()
Can be used to return the average of all columns , It can also be used to return the average value of a specific column or row .
The following example uses AVG() return Products The average price of all the products in the table :
Input ▼
SELECT AVG(prod_price) AS avg_price
FROM Products;
Output ▼
avg_price
-------------
6.823333
analysis ▼
this SELECT Statement return value avg_price , It contains Products For all products in the table
The average price . As the first 7 Lesson description , avg_price It's an alias .
AVG() It can also be used to determine the average value of a specific column or row . The following example returns a specific supply
The average price of a product offered by a supplier :
Input ▼
SELECT AVG(prod_price) AS avg_price
FROM Products
WHERE vend_id = 'DLL01';
Output ▼
avg_price
-----------
3.8650
analysis ▼
This article SELECT The difference between the statement and the previous one is that , It contains WHERE Clause . this
WHERE Clause only filters out vend_id by DLL01 Products , therefore avg_price Middle return
The returned value is only the average value of the supplier's products .
Be careful : Only for a single column
AVG() It can only be used to determine the average of a particular numeric column , And the column name must be a function parameter
The number gives . To get the average of multiple columns , You have to use multiple AVG() function . Only
An exception is when you want to calculate a value from multiple columns , Later in this lesson, we will talk about .
explain : NULL value
AVG() Function ignores column values as NULL The line of .
9.1.2 COUNT() function
COUNT() Function to count . available COUNT() Determine the number of rows in a table or match a specific
Number of conditional rows .
COUNT() Functions can be used in two ways :
Use COUNT(*) Count the number of rows in the table , Whether a table column contains null values
( NULL ) Or non null .
Use COUNT(column) Count rows with values in a specific column , Ignore NULL value .
The following example returns Customers The total number of customers in the table :
Input ▼
SELECT COUNT(*) AS num_cust
FROM Customers;
Output ▼
num_cust
--------
5
analysis ▼
In this example , utilize COUNT(*) Count all rows , Whatever the value of each column in the row . meter
Values in num_cust Back in .
The following example counts only customers with email addresses :
Input ▼
SELECT COUNT(cust_email) AS num_cust
FROM Customers;
Output ▼
num_cust
--------
3
analysis ▼
This article SELECT Statements use COUNT(cust_email) Yes cust_email Columns with values
Count rows . In this example , cust_email Count as 3 ( Express 5 Only... Of the customers
Yes 3 The customer has an email address ).
explain : NULL value
If you specify a column name , be COUNT() The function ignores that the value of the specified column is NULL The line of , but
If COUNT() The asterisk is used in the function ( * ), Don't ignore .
9.1.3 MAX() function
MAX() Returns the maximum value in the specified column . MAX() Require column name , As shown below :
Input ▼
SELECT MAX(prod_price) AS max_price
FROM Products;
Output ▼
max_price
----------
11.9900
analysis ▼
here , MAX() return Products The price of the most expensive item in the list .
Tips : Use... For non numerical data MAX()
although MAX() Usually used to find the maximum value or date value , But many ( Not all )
DBMS Allows it to be used to return the maximum value in any column , Include the most... In the returned text column
Great value . When used for text data , MAX() Returns the last row sorted by this column .
explain : NULL value
MAX() Function ignores column values as NULL The line of .
9.1.4 MIN() function
MIN() The function of is just the same as MAX() The function is the opposite , It returns the minimum value of the specified column . And MAX()
equally , MIN() Require column name , As shown below :
Input ▼
SELECT MIN(prod_price) AS min_price
FROM Products;
Output ▼
min_price
----------
3.4900
analysis ▼
among MIN() return Products The price of the cheapest item in the list .
Tips : Use... For non numerical data MIN()
although MIN() Usually used to find the minimum value or date value , But many ( Not all )
DBMS Allows it to be used to return the minimum value in any column , Include the most... In the returned text column
Small value . When used for text data , MIN() Returns the first row after the column is sorted .
explain : NULL value
MIN() Function ignores column values as NULL The line of .
9.1.5 SUM() function
SUM() Used to return the sum of the specified column values ( A total of ).
Here's an example , OrderItems Include the actual items in the order , Each item has a corresponding
The number of . The total number of items ordered can be retrieved as follows ( all quantity Sum of values ):
Input ▼
SELECT SUM(quantity) AS items_ordered
FROM OrderItems
WHERE order_num = 20005;
Output ▼
items_ordered
----------
200
analysis ▼
function SUM(quantity) Return the sum of the quantity of all items in the order , WHERE Clause guarantees only
Count the items in an item order .
SUM() It can also be used to sum up the calculated value . In the following example , Total... For each item
item_price*quantity , Get the total order amount :
Input ▼
SELECT SUM(item_price*quantity) AS total_price
FROM OrderItems
WHERE order_num = 20005;
Output ▼
total_price
----------
1648.0000
analysis ▼
function SUM(item_price*quantity) Return the sum of the prices of all items in the order , WHERE
Clause also ensures that only the items in an item order are counted .
Tips : Calculate on multiple columns
As shown in this example , Using standard arithmetic operators , All aggregate functions can be used to perform multiple
Calculation on Columns .
explain : NULL value
SUM() Function ignores column values as NULL The line of .
9.2 Gather different values
above 5 Each aggregation function can be used as follows .
Perform calculations on all lines , Appoint ALL Parameters or do not specify parameters ( because ALL Is the default line
by ).
Contains only different values , Appoint DISTINCT Parameters .
Tips : ALL As the default
ALL Parameters do not need to be specified , Because it's the default behavior . If you don't specify DISTINCT , be
Is assumed to be ALL .
The following example uses AVG() Function returns the average price of products provided by a specific supplier . it
With the above SELECT Same statement , But using the DISTINCT Parameters , So the average value is only
Consider different prices :
Input ▼
SELECT AVG(DISTINCT prod_price) AS avg_price
FROM Products
WHERE vend_id = 'DLL01';
Output ▼
avg_price
-----------
4.2400
analysis ▼
You can see , In the use of the DISTINCT after , In this example avg_price Relatively high , because
For multiple items with the same lower price . Excluding them raises the average price .
Be careful : DISTINCT Cannot be used for COUNT(*)
If you specify a column name , be DISTINCT It can only be used for COUNT() . DISTINCT Out-of-service
On COUNT(*) . Similarly , DISTINCT Column names must be used , Cannot be used for calculations or tables
Da da .
Tips : take DISTINCT be used for MIN() and MAX()
although DISTINCT Technically, it can be used for MIN() and MAX() , But it doesn't actually
valuable . The minimum and maximum values in a column regardless of whether only different values are considered , The results are
It's the same .
explain : Other aggregation parameters
Except for what's introduced here DISTINCT and ALL Parameters , yes , we have DBMS Other parameters are also supported ,
For example, it supports the calculation of subsets of query results TOP and TOP PERCENT . To solve the problem
Somatic DBMS Which parameters are supported , Please refer to the corresponding documentation .
9.3 Combining aggregate functions
All the aggregation function examples so far only involve a single function . But actually , SELECT language
Sentences can contain multiple aggregate functions as needed . Please see the following example :
Input ▼
SELECT COUNT(*) AS num_items,
MIN(prod_price) AS price_min,
MAX(prod_price) AS price_max,
AVG(prod_price) AS price_avg
FROM Products;
Output ▼
num_items price_min price_max price_avg
---------- --------------- --------------- ---------
9 3.4900 11.9900 6.823333
analysis ▼
Here's a single SELECT Statement executed 4 Aggregate calculation , return 4 It's worth ( Products
The number of items in the table , The highest value of product price 、 Minimum and average ).
Be careful : Take the alias
When specifying an alias to include the result of an aggregate function , The actual columns in the table should not be used
name . Although it's legal to do so , But many SQL Implementation does not support , Blurring may occur
Error messages for .
边栏推荐
- Every time I look at my colleagues' interface documents, I get confused and have a lot of problems...
- Retest the cloud native database performance: polardb is still the strongest, while tdsql-c and gaussdb have little change
- 200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration
- CSDN blog operation team 2022 H1 summary
- LVGL 8.2 Image
- [STL source code analysis] iterator
- LVGL 8.2 Simple Colorwheel
- 语音信号处理-基础(五):傅立叶变换
- LeetCode Algorithm 86. Separate linked list
- Mysql database foundation: views and variables
猜你喜欢

时间复杂度与空间复杂度

China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market

ArrayList and sequence table

OceanBase 安装 yum 源配置错误及解决办法

The precision problem of depth texture in unity shader - stepping pit - BRP pipeline (there is no solution, it is recommended to replace URP)

高通发布物联网案例集 “魔镜”、数字农业已经成为现实

软件测试工程师面试基础题(应届生和测试小菜必备)最基础的面试题

小程序中读取腾讯文档的表格数据

电商两位大佬花边新闻刷屏,代表电商回归正常,将有利于实体经济

DQN笔记
随机推荐
LVGL 8.2 Checkboxes as radio buttons
MySQL导出sql脚本文件
China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market
LVGL 8.2 Image
sCrypt 中的 ECDSA 签名验证
[rust weekly database] num bigint - large integer
LVGL 8.2 Simple Colorwheel
Every time I look at my colleagues' interface documents, I get confused and have a lot of problems...
科普达人丨漫画图解什么是eRDMA?
SGD has many improved forms. Why do most papers still use SGD?
深潜Kotlin协程(十七):演员
训练一个图像分类器demo in PyTorch【学习笔记】
Double-DQN笔记
Rejuvenated Dell and apple hit each other, and the two old PC enterprises declined rapidly
煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗
LVGL 8.2 Drop down in four directions
LVGL 8.2图片缩放及旋转
[STL source code analysis] container (to be supplemented)
LVGL 8.2 Simple Drop down list
语音识别-基础(一):简介【语音转文本】