Advanced 5: grouping queries
Syntax:
the SELECT list of queries
from table
[where] filter criteria
field group by grouping
[order by sorting fields];
Note: The
list of queries have special requirements field after the group functions and group by
Features:
1, the packet filter criteria in the query into two categories
data source | position | Keyword | |
---|---|---|---|
Packet filtering ago | Original table | group by front | where |
After the screening group | After grouping result set | group by back | having |
Grouping function to make sure the conditions placed in the HAVING
Group by clause supports a single field grouping, grouping multiple fields, functions, expressions, can take on the final sorting
Grouping function:
COUNT
SUM
max
min
AVG
#查询每个部门的员工个数
SELECT COUNT(*) FROM employees WHERE department_id=90;
#案例1:查询每个工种的员工平均工资
SELECT AVG(salary),job_id
FROM employees
GROUP BY job_id;
Add filter criteria grouped
#案例1 查询那个部门的员工数>2
#1.查询每个部门的员工个数
#2.根据1的结果进行筛选,查询那个部门的员工个数>2
/*
不能用where因为where是从你原始表里面筛选 并且更在from后面 而现在要求是在结果的新建表里面进行筛选 用having
*/
select count(*),department_id from employees
group by department_id
having count(*)>2;
#案例2: 查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资
select
max(salary),
job_id
from
employees
where commission_pct is not null
group by job_id
having max(salary)>12000;
#按多个字段分组
#案例:查询每个部门每个工种的平均工资
select avg(salary),department_id,job_id from employees
group by department_id,job_id;
#添加排序
#案例:查询每个部门每个工种的平均工资,并且按平均工资的高低显示
SELECT
AVG(salary),
department_id,
job_id
FROM
employees
WHERE department_id IS NOT NULL
GROUP BY department_id,
job_id
HAVING AVG(salary)>10000
order by avg(salary) desc;