当前位置:网站首页>Advanced SQL query

Advanced SQL query

2022-06-09 07:46:00 GUTSZ

1. Aggregate query

1. Common aggregate functions are :
 Insert picture description here

1.1count function

count Used to query the number of entries .
1.count usage 1:
 Insert picture description here
2.count usage 2:
 Insert picture description here
You can query all the data (null+ Not null), Compatibility is not very good ,mysql have access to , Other databases may not work .
3.count usage 3:
 Insert picture description here
4. summary :

In different count Statistical scenario , Use a different count Inquire about
(1) To query the quantity of all data (null+ Not null) Just use ->count(*)
(2) If you want to query all non Null You can use count( Field name ), It is not recommended to use , For the statistics of special scenarios, consider using count(*)+where Conditions of the query

1.2sum Sum Statistics

 Insert picture description here
And statistics , If there is null, Or statistics of non integer values , The result is that only valid integer values are counted .

1.3avg Calculate average

 Insert picture description here
avg When calculating the average , If there are data that do not conform to the specifications ( Such as NULL) This row of data will be discarded directly , Do not participate in the operation .

1.4max Maximum

 Insert picture description here

1.5min minimum value

 Insert picture description here
 Insert picture description here

1.6iffull function

1. Judge whether it is null Function of , You can take two parameters , If the first parameter is not null, Then return the first parameter , Otherwise, the second parameter is returned .
2. grammar :

IFNULL(expression_1,expression_2);

If expression_1 Not for NULL, be IFNULL The function returns expression_1, Otherwise return to expression_2 Result .
Example :

SELECT IFNULL(1,0); -- returns 1 

3. The total score is Null The problem of :
 Insert picture description here
Use ifnull Function to solve the above problem :

 Insert picture description here

2. Group query group by

1. grammar :
group by Is in where After the query , And its execution sequence is also in where after .

select column1, sum(column2), .. from table group by column1,column3;

2. Example :
Query the maximum salary for each role 、 Minimum and average wages .
 Insert picture description here

2.1 Grouping query criteria having

1.group by⼦ Sentence into ⾏ After grouping , You need to re group the results ⾏ Conditional filtering , Can't make ⽤ where sentence ,⽽ Need to use having.having Query for filtering group by Data in .
2.having Is in group by Then the conditions , Its execution sequence is also in group by after .
3. Example :
It shows that the average wage is lower than 1500 And its average salary :
 Insert picture description here

原网站

版权声明
本文为[GUTSZ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021405013022.html