--部门表
create table t_dept
(
d_id number primary key ,
d_name varchar2(20)
);
create sequence dept_sequence
start with 1
increment by 1;
--员工表
create table t_emp
(
e_id number primary key ,
d_id number references t_dept(d_id),
e_name varchar2(20)
);
create sequence emp_sequence
start with 100
increment by 1;
insert into t_dept values(dept_sequence.nextval,'一部');
insert into t_dept values(dept_sequence.nextval,'二部');
select * from t_dept;
--“一部”插入4个员工
insert into t_emp values(emp_sequence.nextval,2,'张一');
insert into t_emp values(emp_sequence.nextval,2,'张二');
insert into t_emp values(emp_sequence.nextval,2,'张三');
insert into t_emp values(emp_sequence.nextval,2,'张四');
--“二部”插入2个员工
insert into t_emp values(emp_sequence.nextval,3,'李一');
insert into t_emp values(emp_sequence.nextval,3,'李一');
select * from t_emp;
目的:查询员工人数最少的部门
知识点:分组函数,排序,子查询,rownum
sql语句如下:
select * from (select count(*) coun,d_id deptId from t_emp group by d_id order by coun asc) where rownum=1
分析:
第一步:select count(*) coun,d_id deptId from t_emp group by d_id 查询t_emp表,根据部门d_id分组查询各部门的人数以d_id
第二步:select count(*) coun,d_id deptId from t_emp group by d_id order by coun asc 再orderby coun asc ,这样就按照人数升序排序,这样就第一条就是人数最少的
第三步:子查询,select * from (select count(*) coun,d_id deptId from t_emp group by d_id order by coun asc) where rownum=1 ,因为Oracle不支持select top 1,当要取第一条数据的时候,要用到oracel给查询分配的rownum列,where rownum=1就取到第一条数据了
结果如下:
---------------------------------------
counn deptid
---------------------------------------
2 3