[MySQL] How to group the data in the table?

How to group the data in the table?

In MySQL, GROUP BYclauses can be used to divide the data in the table into several groups.

Example: The employee table employees contains different departments

insert image description here

GROUP BYRequirement 1: I want to query the difference between the average salary of different departments, so I can use clauses in the query statement :

SELECT department_id,AVG(salary)
FROM employees
GROUP BY department_id;

Requirement 2: Query the average salary of each department_id and job_id

SELECT department_id,job_id,AVG(salary)
FROM employees
GROUP BY department_id,job_id;
# 或
SELECT job_id,department_id,AVG(salary)
FROM employees
GROUP BY job_id,department_id;

GROUP BY usage points

1. SELECTFields of non-group functions appearing in must be declared in GROUP BY. Conversely, GROUP BYfields declared in may not appear SELECTin .

For example, in the following paragraph of SQL, SELECTif the latter job_iddoes not appear in GROUP BYthe latter, an error will be reported when running.

SELECT department_id,job_id,AVG(salary)
FROM employees
GROUP BY department_id;

2. Location of use

GROUP BYStatement FROMafter, WHEREafter, ORDER BYbefore, LIMITbefore.

3. New feature: GROUP BYuse inWITH ROLLUP

After using WITH ROLLUPthe keyword, add a record after all queried group records, and this record calculates the sum of all queried records, that is, the number of statistical records.

SELECT department_id,AVG(salary)
FROM employees
WHERE department_id
GROUP BY department_id WITH ROLLUP;

When used ROLLUP, clauses cannot be used at the same time ORDER BYfor ordering results, i.e. ROLLUOPand ORDER BYare mutually exclusive.

HAVING

1. If an aggregate function is used in the filter condition , it must be replaced HAVINGwith WHEREOtherwise, an error will be reported. In addition, HAVINGit must be declared at GROUP BYthe front.
For example:

SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000;

2. In development, HAVINGthe premise we use is that it is used in SQL GROUP BY.

3. When the filter condition includes aggregate function and others, write the aggregate function condition after HAVING, and write other filter conditions after WHERE, which is more efficient than using only HAVING.
For example:

SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN (10,20,30,40)
GROUP BY department_id 
HAVING MAX(salary) > 10000;

Guess you like

Origin blog.csdn.net/hold_on_qlc/article/details/130479214