动力节点经典34道MySQL面试题(上)

动力节点经典34道MySQL面试题(上)_第1张图片

表dept

动力节点经典34道MySQL面试题(上)_第2张图片

表emp

动力节点经典34道MySQL面试题(上)_第3张图片

表salgrade

1~取得每个部门的最高薪水的人员名称
SELECT t.*,e.ENAME
FROM (SELECT DEPTNO,max(SAL) maxsal FROM emp GROUP BY DEPTNO) t
JOIN emp e
ON e.DEPTNO=t.DEPTNO and e.SAL=t.maxsal
2~哪些人的薪水在部门平均薪水之上
SELECT t.*,e.ENAME,e.SAL
FROM (SELECT DEPTNO,avg(SAL) avgsal
FROM emp
GROUP BY DEPTNO
) t
JOIN emp e
ON e.DEPTNO=t.DEPTNO AND e.SAL > t.avgsal
ORDER BY DEPTNO
3~取得部门中(所有人的)平均薪水等级
SELECT t.*,s.GRADE
FROM (SELECT DEPTNO,avg(SAL) avgsal
FROM emp e
GROUP BY DEPTNO
) t
JOIN salgrade s
ON t.avgsal BETWEEN s.LOSAL AND s.HISAL
ORDER BY DEPTNO
4~取得部门中所有人的平均的薪水等级
SELECT t.DEPTNO,avg(salgrade)
FROM (SELECT e.SAL,s.GRADE salgrade,e.DEPTNO
FROM emp e
JOIN salgrade s
ON e.SAL BETWEEN s.LOSAL AND s.HISAL
) t
GROUP BY DEPTNO
ORDER BY DEPTNO
5~不准用组函数(max),取得最高的薪水(给出两种解决方案)
方法一:
SELECT SAL,ENAME
FROM emp
ORDER BY SAL DESC
LIMIT 1
方法二:
SELECT SAL maxsal
FROM emp
WHERE SAL NOT IN(SELECT distinct e1.SAL
FROM emp e1
JOIN emp e2
ON e1.SAL < e2.SAL)
6~取得平均薪水最高的部门的部门编号
方法一:
SELECT t.DEPTNO,t.avgsal avgsal
FROM (SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
ORDER BY avgsal DESC
)t
LIMIT 1
方法二:
SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
HAVING avgsal =(SELECT max(t.avgsal)
FROM (SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
ORDER BY DEPTNO) t)
7~取得平均薪水最高的部门的部门名称
方法一:
SELECT d.DNAME
FROM(SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
ORDER BY avgsal DESC
) t
JOIN dept d
ON d.DEPTNO=t.DEPTNO
LIMIT 1
方法二:
SELECT d.DNAME
FROM dept d
JOIN (SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
HAVING avgsal =(SELECT max(t.avgsal)
FROM (SELECT DEPTNO,avg(sal) avgsal
FROM emp
GROUP BY DEPTNO
ORDER BY DEPTNO) t)) t2
ON t2.DEPTNO=d.DEPTNO
8~求平均薪水的等级最低的部门的部门名称
SELECT d.DEPTNO,d.DNAME
FROM dept d
GROUP BY DEPTNO,DNAME
HAVING DEPTNO=(SELECT t.DEPTNO
FROM (SELECT e.DEPTNO,avg(SAL) avgsal
FROM emp e
GROUP BY DEPTNO
) t
JOIN salgrade s
ON t.avgsal BETWEEN s.LOSAL AND s.HISAL
ORDER BY GRADE
LIMIT 1)
9~取得薪水最高的前五名员工
SELECT ENAME,SAL
FROM emp
ORDER BY SAL DESC
LIMIT 5
10~取得薪水最高的第六到第十名员工
SELECT ENAME,SAL
FROM emp
ORDER BY SAL DESC
LIMIT 5,5


 

你可能感兴趣的:(MySQL)