How to group the data in the table?
In MySQL, GROUP BY
clauses can be used to divide the data in the table into several groups.
Example: The employee table employees contains different departments
GROUP BY
Requirement 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. SELECT
Fields of non-group functions appearing in must be declared in GROUP BY
. Conversely, GROUP BY
fields declared in may not appear SELECT
in .
For example, in the following paragraph of SQL, SELECT
if the latter job_id
does not appear in GROUP BY
the 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 BY
Statement FROM
after, WHERE
after, ORDER BY
before, LIMIT
before.
3. New feature: GROUP BY
use inWITH ROLLUP
After using WITH ROLLUP
the 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 BY
for ordering results, i.e. ROLLUOP
and ORDER BY
are mutually exclusive.
HAVING
1. If an aggregate function is used in the filter condition , it must be replaced HAVING
with WHERE
Otherwise, an error will be reported. In addition, HAVING
it must be declared at GROUP BY
the front.
For example:
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000;
2. In development, HAVING
the 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;