当前位置:网站首页>Alibaba cloud AI training camp -sql foundation 2: query and sorting
Alibaba cloud AI training camp -sql foundation 2: query and sorting
2022-06-09 05:22:00 【xatop】
One 、SELECT Sentence basis
1.1 Select data from the table
1.2 Select qualified data from the table
1.3 The law of correlation
Two 、 Arithmetic operators and comparison operators
2.1 Arithmetic operator
2.2 Comparison operator
2.3 Common rules
3、 ... and 、 Logical operators
3.1 NOT Operator
3.2 AND Operators and OR Operator
3.3 Precedence through parentheses
3.4 Truth table
3.5 contain NULL True value at
Exercises - The first part
Exercises 1
Exercises 2
Exercises 3
Exercises 4
Four 、 Aggregate queries on tables
4.1 Aggregate functions
4.2 Use aggregate functions to remove duplicate values
4.3 Common rules
5、 ... and 、 Group tables
5.1 GROUP BY sentence
5.2 The aggregate key contains NULL when
5.3 GROUP BY Writing position
5.4 stay WHERE Used in clauses GROUP BY
5.5 Common mistakes
6、 ... and 、 Specify conditions for aggregate results
6.1 use HAVING Get specific groups
6.2 HAVING characteristic
7、 ... and 、 Sort query results
7.1 ORDER BY
7.2 ORDER BY Alias can be used for column names in
Exercises - The second part
Exercises 5
Exercises 6
Exercises 7
SQL Training camp page address :AI Training camp SQL- Alibaba cloud Tianchi
Tianchi Longzhu program training camp address :AI Training camp - Alibaba cloud Tianchi
One 、SELECT Sentence basis
1.1 Select data from the table
SELECT sentence
When selecting data from a table, you need to use SELECT sentence , That is, only from the list (SELECT) Meaning of necessary data . adopt SELECT The process of querying and selecting the necessary data is called matching query or query (query).
basic SELECT The statement contains SELECT and FROM Two clauses (clause). Examples are as follows :
SELECT < Name >,
FROM < Table name >;
among ,SELECT Clause lists the names of the columns you want to query from the table , and FROM Clause specifies the name of the table from which the data is selected .
1.2 Select qualified data from the table
WHERE sentence
When you don't need to take out all the data , Instead, choose to meet “ The commodity category is clothes ”“ The sales unit price is in 1000 Above JPY ” When waiting for data under certain conditions , Use WHERE sentence .
SELECT Statement passing WHERE Clause to specify the conditions for querying data . stay WHERE Clause can specify “ The value of a column is equal to this string ” perhaps “ The value of a column is greater than this number ” Equal conditions . Execute... With these conditions SELECT sentence , You can query only the records that meet this condition .
SELECT < Name >, ……
FROM < Table name >
WHERE < Conditional expression >;
Compare the output results of the following two :
-- Used to select product type List as clothes ’ The record of SELECT sentence
SELECT product_name, product_type
FROM product
WHERE product_type = ' clothes ';
-- You can also select columns that are not query criteria ( The condition column is different from the output column )
SELECT product_name
FROM product
WHERE product_type = ' clothes ';
1.3 The law of correlation
- asterisk (*) Stands for all columns .
- SQL You can use line breaks at will in , Does not affect statement execution ( But don't insert a blank line ).
- You need to use double quotation marks when setting Chinese alias (") Cover up .
- stay SELECT Use in statement DISTINCT You can delete duplicate lines .
- Comments are SQL The part of a statement used to identify instructions or precautions . It is divided into 1 Line notes "-- " And multiline comments "/* */".
-- When you want to query all columns , You can use asterisks representing all columns (*).
SELECT *
FROM < Table name >;
-- SQL Statement can be used AS Keyword to alias a column ( Double quotation marks are required when using Chinese (“”)).
SELECT product_id AS id,
product_name AS name,
purchase_price AS " Purchase unit price "
FROM product;
-- Use DISTINCT Delete product_type Duplicate data in column
SELECT DISTINCT product_type
FROM product;
Two 、 Arithmetic operators and comparison operators
2.1 Arithmetic operator
SQL The main operators of the four operations that can be used in the statement are as follows :
| meaning | Operator |
|---|---|
| Add | + |
| Subtraction | - |
| Multiplication | * |
| division | / |
2.2 Comparison operator
-- Take out sale_price As a 500 The record of
SELECT product_namep, roduct_type
FROM product
WHERE sale_price = 500;
SQL Common comparison operators are as follows :
| Operator | meaning |
|---|---|
| = | and ~ equal |
| <> | and ~ It's not equal |
| >= | Greater than or equal to ~ |
| > | Greater than ~ |
| <= | Less than or equal to ~ |
| < | Less than ~ |
2.3 Common rules
- SELECT You can use constants or expressions in clauses .
- When using the comparison operator, be sure to pay attention to the position of the unequal sign and the equal sign .
- String type data is sorted in dictionary order in principle , It can't be confused with the size order of numbers .
- Hope to choose NULL When recording , You need to use... In conditional expressions IS NULL Operator . I hope the choice is not NULL When recording , You need to use... In conditional expressions IS NOT NULL Operator .
The relevant code is as follows :
-- SQL You can also use operational expressions in statements
SELECT product_name, sale_price, sale_price * 2 AS "sale_price x2"
FROM product;
-- WHERE Clause can also be used in conditional expressions
SELECT product_name, sale_price, purchase_price
FROM product
WHERE sale_price-purchase_price >= 500;
/* Use an unequal sign on a string
First create chars And insert data
Select a value greater than ‘2’ Of SELECT sentence */
-- DDL: Create table
CREATE TABLE chars
(chr CHAR(3)NOT NULL,
PRIMARY KEY(chr));
-- Select a value greater than '2' Data. SELECT sentence ('2' For the string )
SELECT chr
FROM chars
WHERE chr > '2';
-- selection NULL The record of
SELECT product_name,purchase_price
FROM product
WHERE purchase_price IS NULL;
-- Select not NULL The record of
SELECT product_name,purchase_price
FROM product
WHERE purchase_price IS NOT NULL;
3、 ... and 、 Logical operators
3.1 NOT Operator
Want to express “ No ……” when , Except for the above <> Outside operator , There is another negative expression 、 Use a wider range of operators :NOT.
NOT Not to be used alone , Here's an example :
-- The selected sales unit price is greater than or equal to 1000 The record of Japanese yen
SELECT product_name, product_type, sale_price
FROM product
WHERE sale_price >= 1000;
-- To the code list 2-30 Add... To the query conditions of NOT Operator
SELECT product_name, product_type, sale_price
FROM product
WHERE NOT sale_price >= 1000;
3.2 AND Operators and OR Operator
When you want to use multiple query criteria at the same time , have access to AND perhaps OR Operator .
AND amount to “ also ”, Similar to the intersection in Mathematics ;
OR amount to “ perhaps ”, Similar to the union set in Mathematics .
As shown in the figure below :
AND Operator working effect diagram

OR Operator working effect diagram

3.3 Precedence through parentheses
If you want to find such a product , What to do with ?
“ The commodity category is office supplies ” also “ The registration date is 2009 year 9 month 11 Day or 2009 year 9 month 20 Japan ”
The ideal result is “ Punch ”, But when you enter the following information , Will get the wrong result
-- Write the query condition to the condition expression intact , Will get the wrong result
SELECT product_name, product_type, regist_date
FROM product
WHERE product_type = ' Office Supplies '
AND regist_date = '2009-09-11'
OR regist_date = '2009-09-20';
The reason for the mistake is yes AND Operator takes precedence over OR Operator , Want to give priority to OR operation , have access to Brackets :
-- Make... By using parentheses OR The operator precedes AND Operator execution
SELECT product_name, product_type, regist_date
FROM product
WHERE product_type = ' Office Supplies '
AND ( regist_date = '2009-09-11'
OR regist_date = '2009-09-20');
3.4 Truth table
How to understand complex operations ?
When you encounter a statement with complex conditions , It's not easy to understand the meaning of a sentence , You can use Truth table To sort out the logical relationship .
What is true value ?
The three operators described in this section NOT、AND and OR Called logical operators . The logic mentioned here means to operate on the truth value . Truth value Is the value is true (TRUE) Or false (FALSE) Value of one of them .
for example , about sale_price >= 3000 For this query condition , because product_name As a ' motion T T-shirt ' The record of sale_price Is the value of the column 2800, So it returns false (FALSE), and product_name As a ' pressure cooker ' The record of sale_price Is the value of the column 5000, So back to true (TRUE).
AND Operator **:** Returns true when the truth values on both sides are true , In addition, all return false .
OR Operator **:** As long as one of the truth values on both sides is not false, it returns true , False is returned only if the true values on both sides are false .
NOT Operator **:** Just simply convert true into false , Convert false to true .
Truth table

The query conditions are P AND(Q OR R) Truth table of

3.5 contain NULL True value at
NULL The truth result of is neither true , It's not false , Because I don't know such a value .
How to express it ?
At this time, the true value is the third value besides true and false —— Not sure (UNKNOWN). This third value does not exist in general logical operations .SQL Other languages basically use only true and false truth values . In contrast to the usual logical operation called binary logic , Only SQL The logical operation in is called ternary logic .
Three valued logic AND and OR The truth table is :

Exercises - The first part
Exercises 1
Write a SQL sentence , from product( goods ) Select from the table “ Registration date (regist stay 2009 year 4 month 28 After the day ” The goods , Query results should contain product_name and regist_date Two .
result :select product_name,regist_date from product where regist_date>'2009-04-28';
Exercises 2
Please say yes to product The table is executed as follows 3 strip SELECT The return result of statement .
①
SELECT *
FROM product
WHERE purchase_price = NULL;
result : Returns an empty .
②
SELECT *
FROM product
WHERE purchase_price <> NULL;
result : Returns an empty .
③
SELECT *
FROM product
WHERE product_name > NULL;
result : Returns an empty .
summary : Use =、<>、> Wait a minute NULL Operate as a value , If you want to check the null value , Need to use IS NULL、IS NOT NULL To operate .
Exercises 3
Code list 2-22(2-2 section ) Medium SELECT Statements can be made from product Take out from the table “ Unit sales price (saleprice) Compared with the purchase price (purchase price) Higher than 500 Above JPY ” The goods . Please write two items that can get the same result SELECT sentence . The results are shown below .
product_name | sale_price | purchase_price
-------------+------------+------------
T shirt | 1000 | 500
motion T T-shirt | 4000 | 2800
pressure cooker | 6800 | 5000
sentence 1:select * from product where sale_price-purchase_price>500;
sentence 2:select * from product where not (sale_price-purchase_price<=500);
Exercises 4
Please write a SELECT sentence , from product Select from the table to meet “ After 10% discount on unit sales price, the profit is higher than 100 Japanese yen office supplies and kitchen utensils ” Record of conditions . The query results should include product_name Column 、product_type And the profit after 10% discount on the sales unit price ( The alias is set to profit).
Tips : 10% off the unit price , Can pass saleprice Multiply the value of the column by 0.9 get , The profit can be subtracted from this value purchase_price The value of the column gets .
result :select * from product where sale_price*0.9-purchase_price>100;
Four 、 Aggregate queries on tables
4.1 Aggregate functions
SQL 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
Please follow the data in Chapter 1 , Use the following functions :
-- 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;
4.2 Use aggregate functions to remove 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;
4.3 Common rules
- 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 .
5、 ... and 、 Group tables
5.1 GROUP BY sentence
Previously, aggregation functions were used to process the data of the entire table , When you want to group and summarize ( namely : Summarize the existing data according to a certain column ),GROUP BY Can help you :
SELECT < Name 1>,< Name 2>, < Name 3>, ……
FROM < Table name >
GROUP BY < Name 1>, < Name 2>, < Name 3>, ……;
See if you can use GROUP BY The difference of sentences :
-- Count the number of rows of data by commodity category
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type;
-- Not included GROUP BY
SELECT product_type, COUNT(*)
FROM product
Cut the table according to the commodity type

such ,GROUP BY Clause groups the table like a cake . stay GROUP BY The column specified in the clause is called Polymerization bond perhaps Group columns .
5.2 The aggregate key contains NULL when
The purchase unit price (purchase_price) As an example of an aggregate bond :
SELECT purchase_price, COUNT(*)
FROM product
GROUP BY purchase_price;
At this point NULL As a special set of data
5.3 GROUP BY 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
5.4 stay WHERE Used in clauses GROUP BY
SELECT purchase_price, COUNT(*)
FROM product
WHERE product_type = ' clothes '
GROUP BY purchase_price;
5.5 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 .
6、 ... and 、 Specify conditions for aggregate results
6.1 use HAVING Get specific groups
Use table GROUP BY After grouping , How can I just take out two of them ?

here WHERE Is not workable , because ,WHERE Clause can only specify records ( That's ok ) Conditions , It cannot be used to specify the conditions of the group ( for example ,“ The number of data rows is 2 That's ok ” perhaps “ The average value is 500” etc. ).
Can be in GROUP BY After use HAVING Clause .
HAVING The usage of is similar to WHERE
6.2 HAVING characteristic
HAVING Clause is used to filter groups , You can use 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 ';
7、 ... and 、 Sort query results
7.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 .
SELECT < Name 1>, < Name 2>, < Name 3>, ……
FROM < Table name >
ORDER BY < Sort base column 1>, < Sort base column 2>, ……
The default is ascending , 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;
7.2 ORDER BY Alias can be used for column names in
As mentioned earlier GROUP BY I mentioned ,GROUP BY Cannot use... In clause SELECT Clause , But in ORDER BY You can use aliases in clauses . Why is it GROUP BY Not in... But in ORDER BY It's ok ?
This is because 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 - The second part
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';
result :1、 Comments cannot be written in sql Statement inside ;
2、sum Only numeric fields can be aggregated ;
3、where Need to be in group by front ;
4、select Medium product_id Not in the group by Field ;
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 .
product_type | sum | sum
-------------+------+------
clothes | 5000 | 3300
Office Supplies | 600 | 320

result :select product_type,sum(sale_price),sum(purchase_price) from product group by product_type having sum(sale_price)>sum(purchase_price)*1.5;
Exercises 7
We used it before SELECT The sentence is selected product( goods ) All the records in the table . We used ORDERBY Clause to specify the sort order , But now I can't remember how it was designated . Please refer to the following execution results , reflection ORDERBY The content of the clause .

result :select * from product order by regist_date desc,sale_price;
The answers to the exercises can be found in the official account of Tianchi. : Tianchi big data research platform reply :SQL Training camp obtain .
边栏推荐
猜你喜欢

2022-06-清华管理学-清华大学-宁向东

MRNA factory| quantitative detection of LNP encapsulated RNA content by ribogreen

Apache Devlake 代码库导览

AI video cloud: a good wife in the era of we media

STM32 FreeRTOS task Basics

June 2022 Tsinghua Management Tsinghua University Ning Xiangdong

A few minutes to understand the Flink waterline

三方账号授权登录系统设计思路

Apache devlake code base guide

内网渗透 - 哈希传递攻击
随机推荐
Good hazelnut comes from Liaoyang!
Number that appears only once -leetcode
[C language] all the experts are double cultivators. At the grammatical level, they are almost plain and plain. They never show off their skills. They show off their ideas!
Program implementation of inserting, updating and deleting in Oracle Internet cafe design
How to change the color of WPS ppt background picture
优视慕V8投影仪,打开高清新“视”界
myql报错 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
The difference between traditional method and lean method
2022年茶艺师(中级)考试题模拟考试题库及模拟考试
Data Summit 2022 大会资料分享(共23个)
^26浏览器的内核
Test question bank and online simulation test for operation certificate of main principals of hazardous chemical business units in 2022
Analysis of reentrantlock source code of AQS
Pull down the new project code and make it red
Previous improvements of CSDN products (up to issue 29)
Kube dns yaml
P1779 Xiaohu's springboard
Li Kou today's question -1037 Effective boomerang
How WPS ppt pictures come out one by one
Vector of STL