group by 表示分组,必须和聚合函数(max,min,avg,sum,count)一起使用,作用在于通过某个字段查询该字段里的最大,最小,平均,总数和计数。
例子:
已知表一dept_emp有四个字段,分别为dept_no(部门编号),emp_no(员工编号),hire_date(入职时间),end_date(离职时间)。其中,离职时间为“9999_01_01”表示在职状态,表二department(部门表),有两个字段,分别为dept_no(部门编号),dept_name(部门名称),求:
1.每个部门在职的员工人数;
2.每个部门名在职人数;
首先看第一题:
提取关键字:
a.每个部门(按部门进行分组即group by dept_no);
b.在职的员工(where end_date=‘9999_01_01’);
c.员工人数(count(emp_no))
完整的sql语句:
select
dept_no,
count(emp_no)
from
dept_emp
where
end_date='9999_01_01'
group by
dept_no;
再看第二题,要求查询出部门编号对应的部门名,那么就要用到第二张表了。完整的sql如下:
select
(select d.dept_name from department d where d.dept_no=de.dept_no) as 部门,
count(emp_no) as 人数
from
dept_emp de
where
de.hire_date='9999_01_01'
group by
de.emp_no;