当前位置:网站首页>MySQL learning record (5)
MySQL learning record (5)
2022-07-02 21:29:00 【White_ Silence (Learning version)】
1. Aggregate functions
1.1SQL The function used for aggregation in is called aggregate function . The following five are the most commonly used aggregate functions :
- COUNT: Count the number of records in the table ( Row number )
- SUM: Calculate the total value of the data in the numerical column of the table
- AVG: Calculate the average value of the data in the numerical column in the table
- MAX: Find the maximum value of the data in any column of the table
- MIN: Find the minimum value of data in any column in the table
practice :
-- Calculate the number of rows of all data ( contain NULL)
SELECT COUNT(*) FROM product;
-- Calculation NULL Number of rows of data other than
SELECT COUNT(purchase_price) FROM product;
-- Calculate the total value of sales unit price and purchase unit price
SELECT SUM(sale_price), SUM(purchase_price) FROM product;
-- Calculate the average of sales unit price and purchase unit price
SELECT AVG(sale_price), AVG(purchase_price) FROM product;
-- MAX and MIN It can also be used for non numerical data
SELECT MAX(regist_date), MIN(regist_date) FROM product; 1.2 Use aggregate functions to eliminate duplicate values
-- Calculate the number of data rows after removing duplicate data
SELECT COUNT(DISTINCT product_type)
FROM product;
-- Whether to use DISTINCT The difference in action (SUM function )
SELECT SUM(sale_price), SUM(DISTINCT sale_price)
FROM product;1.3 matters needing attention
- COUNT The result of the function varies according to the parameters .COUNT(*) It will contain NULL The number of rows of data , and COUNT(< Name >) You'll get NULL Number of rows of data outside .
- The aggregate function will NULL Ruled out . but COUNT(*) exception , Does not rule out NULL.
- MAX/MIN The function applies to columns of almost all data types .SUM/AVG The function is only applicable to columns of numeric type .
- When you want to calculate the type of value , Can be in COUNT In the parameters of the function DISTINCT.
- Use... In the arguments of aggregate functions DISTINCT, Duplicate data can be removed .
2. Group tables
2.1GROUP BY sentence ( grouping )
--group by grammar
SELECT < Name 1>,< Name 2>, < Name 3>, ……
FROM < Table name >
GROUP BY < Name 1>, < Name 2>, < Name 3>, ……;
-- Count the number of rows of data by commodity category
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type;
--GROUP BY The columns in the clause are called aggregate columns or grouping keys
-- Not included GROUP BY
SELECT product_type, COUNT(*)
FROM product

2.2GROUP BY Statement writing position
GROUP BY There are strict requirements for the writing order of clauses , Failure to comply with the requirements will result in SQL Unable to execute normally , The clauses that have appeared so far Writing **** The order by :
1**.**SELECT → 2. FROM → 3. WHERE → 4. GROUP BY
The first three items are used to filter the data ,GROUP BY Process the filtered data
SELECT purchase_price, COUNT(*)
FROM product
WHERE product_type = ' clothes '
GROUP BY purchase_price;
2.3 Common mistakes
When using aggregate functions and GROUP BY When clause , Common mistakes are :
- At the end of the aggregate function SELECT Clause writes columns other than aggregate keys Use COUNT Wait for the aggregate function ,SELECT If the column name appears in the clause , Can only be GROUP BY The column name specified in clause ( That's the aggregate bond ).
- stay GROUP BY Use column aliases in clause SELECT Clause can be passed through AS To specify an alias , But in GROUP BY Alias cannot be used in . Because in DBMS in ,SELECT Clause in GROUP BY Execute after clause .
- stay WHERE Aggregate functions are used in The reason is that the aggregate function is used only if the result set has been determined , and WHERE Still in the process of determining the result set , So contradictions can lead to errors . If you want to specify conditions , Can be in SELECT,HAVING( I'll talk about ) as well as ORDER BY The aggregate function is used in clause .
3. Specify conditions for aggregate results
3.1 utilize HAVING Get specific groups
HAVING Usage is similar. WHERE , But the two are different for the object ,HAVING For group ,WHERE For the line ( Record ).
3.2HAVING characteristic
HAVING Clause is used to filter groups , have access to Numbers 、 Aggregate functions and GROUP BY The column name specified in ( Polymerization bond ).
-- Numbers
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type
HAVING COUNT(*) = 2;
-- Wrong form ( because product_name Not included in GROUP BY In the aggregate bond )
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type
HAVING product_name = ' Ball pen ';4. Sort query results
4.1 ORDER BY
SQL The execution results in are arranged randomly , When you need to sort in a specific order , Can be used ORDER BY Clause .
ORDER BY grammar :
SELECT < Name 1>, < Name 2>, < Name 3>, ……
FROM < Table name >
ORDER BY < Sort base column 1>, < Sort base column 2>, ……
-- Default ascending order namely ASC array
-- The descending order is DESC
-- Descending order
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY sale_price DESC;
-- Multiple sort keys
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY sale_price, product_id;
-- When the column name used for sorting contains NULL when ,NULL It will be summarized at the beginning or end .
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY purchase_price;4.2 ORDER BY Aliases can be used in
SQL In the use of HAVING When clause SELECT Of the statement perform **** The order by :
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
among SELECT The order of execution is GROUP BY After Clause ,ORDER BY Before clause . in other words , When in ORDER BY When using aliases in , I already know SELECT The alias set does not exist , But in GROUP BY When you use aliases in, you don't know the existence of aliases , therefore stay ORDER BY You can use aliases in , But in GROUP BY Alias cannot be used in ****.
/* Exercises 5
Please point out the following SELECT All the grammatical errors in the statement .*/
SELECT product_id, SUM(product_name)
-- Ben SELECT There is an error in the statement .
FROM product
GROUP BY product_type
WHERE regist_date > '2009-09-01';
-- error 1: Wrong aggregate key , GROUP BY The order of execution is SELECT Before ,product_type There is no in select In the sentence
-- error 2: The writing order is wrong ,WHERE The clause should be in GROUP BY Before Exercises 6
Please write one SELECT sentence , Find out the sales unit price (sale_price Column ) The total value is greater than the purchase unit price (purchase_price Column ) Total value 1.5 Times the commodity category . The results are shown below .
select product_type, sum(sale_price), sum(purchase_price)
from product
WHERE (select sum(sale_price)>sum(purchase_price)*1.5);
-- Different from the results given 
It should be according to the date regist_date In descending order
ORDER BY regist_date DESC;
边栏推荐
- Construction and maintenance of business website [2]
- A river of spring water flows eastward
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of sound quality head simulators in the global market in 2022
- Send blessings on Lantern Festival | limited edition red envelope cover of audio and video is released!
- Market trend report, technical dynamic innovation and market forecast of China's low gloss instrument
- Check the confession items of 6 yyds
- Construction and maintenance of business websites [7]
- treevalue——Master Nested Data Like Tensor
- Cardinality sorting (detailed illustration)
- MySQL learning notes (Advanced)
猜你喜欢

26 FPS video super-resolution model DAP! Output 720p Video Online

Basic knowledge of tree and binary tree (detailed illustration)

Welfare, let me introduce you to someone

Unexpectedly, there are such sand sculpture code comments! I laughed
![[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)](/img/a7/0b87fa45ef2edd6fac519b40adbeae.gif)
[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)

JDBC | Chapter 4: transaction commit and rollback

5 environment construction spark on yarn
![[dynamic planning] p1220: interval DP: turn off the street lights](/img/b6/405e29ca88fac40caee669a3b7893f.jpg)
[dynamic planning] p1220: interval DP: turn off the street lights

Go language learning summary (5) -- Summary of go learning notes

Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
随机推荐
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
Analysis of enterprise financial statements [4]
Select function
Market trend report, technical dynamic innovation and market forecast of China's low gloss instrument
China plastic bottle and container market trend report, technological innovation and market forecast
Chinese Indian seasoning market trend report, technical dynamic innovation and market forecast
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
Research Report on the overall scale, major manufacturers, major regions, products and applications of capacitive voltage transformers in the global market in 2022
Research Report on the overall scale, major manufacturers, major regions, products and applications of micro hydraulic cylinders in the global market in 2022
Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
Customized Huawei hg8546m restores Huawei's original interface
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of the inverted front fork of the global market in 2022
When Valentine's Day falls on Monday
MySQL learning notes (Advanced)
[shutter] statefulwidget component (image component | textfield component)
Cloud computing technology [2]
Cardinality sorting (detailed illustration)
Basic knowledge of tree and binary tree (detailed illustration)
Accounting regulations and professional ethics [19]
Sword finger offer (II) -- search in two-dimensional array