准备
create table dept (dept1 int ,dept_name varchar(11)) charset=utf8;
create table emp (sid int ,name varchar(11),age int,worktime_start date,incoming int,dept2 int) charset=utf8;insert into dept values(101,'财务'),(102,'销售'),(103,'IT技术'),(104,'行政');INSERT INTO emp VALUES(1789, '张三', 35, '1980-01-01', 4000, 101),(1674, '李四', 32, '1983-04-01', 3500, 101),(1776, '王五', 24, '1990-07-01', 2000, 101),(1568, '赵六', 57, '1970-10-11', 7500, 102),(1564, '荣七', 64, '1963-10-11', 8500, 102),(1879, '牛八', 55, '1971-10-20', 7300, 103),(1668, '钱九', 64, '1963-05-04', 8000, 102),(1724, '武十', 22, '2023-05-08', 1500, 103),(1770, '孙二', 65, '1986-08-12', 9500, 101),(18400, '苟一', 65, '1986-08-12', 1500, 101);
练习
1.找出销售部门中年纪最大的员工的姓名
SELECT name
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = '销售')
ORDER BY age DESC
LIMIT 2;
2.求财务部门最低工资的员工姓名
SELECT name
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = '财务')
ORDER BY incoming ASC
LIMIT 1;
3.列出每个部门收入总和高于9000的部门名称
SELECT d.dept_name
FROM dept d
JOIN emp e ON d.dept1 = e.dept2
GROUP BY d.dept_name
HAVING SUM(e.incoming) > 9000;
4.求工资在7500到8500元之间,年龄最大的人的姓名及部门
SELECT e.name, d.dept_name
FROM emp e
JOIN dept d ON e.dept2 = d.dept1
WHERE e.incoming BETWEEN 7500 AND 8500
ORDER BY e.age DESC
LIMIT 1;
5.找出销售部门收入最低的员工入职时间
SELECT worktime_start
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = '销售')
ORDER BY incoming ASC
LIMIT 1;
6.财务部门收入超过2000元的员工姓名
SELECT name
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = '财务')
AND incoming > 2000;
7.列出每个部门的平均收入及部门名称
SELECT d.dept_name, AVG(e.incoming) AS avg_income
FROM emp e
JOIN dept d ON e.dept2 = d.dept1
GROUP BY d.dept_name;
8.IT技术部入职员工的员工号
SELECT sid
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = 'IT技术');
9.财务部门的收入总和;
SELECT SUM(incoming) AS total_income
FROM emp
WHERE dept2 = (SELECT dept1 FROM dept WHERE dept_name = '财务');
10.找出哪个部门还没有员工入职;
SELECT dept_name
FROM dept
WHERE dept1 NOT IN (SELECT DISTINCT dept2 FROM emp);
11.列出部门员工收入大于7000的部门编号,部门名称;
SELECT d.dept1, d.dept_name
FROM dept d
JOIN emp e ON d.dept1 = e.dept2
GROUP BY d.dept1, d.dept_name
HAVING MAX(e.incoming) > 7000;
12.列出每一个部门的员工总收入及部门名称;
SELECT d.dept_name, SUM(e.incoming) AS total_income
FROM emp e
JOIN dept d ON e.dept2 = d.dept1
GROUP BY d.dept_name;
13.列出每一个部门中年纪最大的员工姓名,部门名称;
SELECT e.name, d.dept_name
FROM emp e
JOIN dept d ON e.dept2 = d.dept1
WHERE e.age = (SELECT MAX(sub_e.age)FROM emp sub_eWHERE sub_e.dept2 = e.dept2
)
ORDER BY e.age DESC;
14.求李四的收入及部门名称
SELECT e.incoming, (SELECT d.dept_name FROM dept d WHERE d.dept1 = e.dept2) AS dept_name
FROM emp e
WHERE e.name = '李四';
15.列出每个部门中收入最高的员工姓名,部门名称,收入,并按照收入降序
SELECT e.name, d.dept_name, e.incoming
FROM emp e
JOIN dept d ON e.dept2 = d.dept1
WHERE e.incoming = (SELECT MAX(incoming) FROM emp WHERE dept2 = e.dept2
)
ORDER BY e.incoming DESC;