MySQL题目练习(正在更新中)


目录

练习环境

MySQL版本为5.6
使用的软件 navicate

第一题

题目:统计每个部门中薪酬最高的员工
知识点:分组排序,多表查询
解题思路:

插入数据
 CREATE TABLE `EMPLOYEE` (
  `ID` varchar(255),
  `Name` varchar(255),
  `Salary` varchar(255),
  `DepartmentID` varchar(255)
 );
INSERT INTO `EMPLOYEE` VALUES ('1', 'Joe', '70000', '1');
INSERT INTO `EMPLOYEE` VALUES ('2', 'Henry', '80000', '2');
INSERT INTO `EMPLOYEE` VALUES ('3', 'Jane', '60000', '2');
INSERT INTO `EMPLOYEE` VALUES ('4', 'Ben', '90000', '1');
CREATE TABLE `DEPARTMENT` (
  `ID` varchar(255),
  `DEPARTMENT` varchar(255)
 );
INSERT INTO `DEPARTMENT` VALUES ('1', 'IT'); 
INSERT INTO `DEPARTMENT` VALUES ('2', 'Sales');
点击查看答案
# 方法一
SELECT
	`Name`,
	Salary,
	DEPARTMENT 
FROM
	( EMPLOYEE INNER JOIN DEPARTMENT ON EMPLOYEE.DepartmentID = DEPARTMENT.ID )
	INNER JOIN ( SELECT DepartmentID, MAX( Salary ) AS MAX_Salary FROM EMPLOYEE GROUP BY DepartmentID ) AS T ON EMPLOYEE.DepartmentID = T.DepartmentID 
	AND EMPLOYEE.Salary = T.MAX_Salary;


# 方法二
SELECT
	*
FROM
	(SELECT 
		`Name` ,Salary,DEPARTMENT as D
	FROM
		EMPLOYEE INNER JOIN DEPARTMENT
	ON 
		EMPLOYEE.DepartmentID = DEPARTMENT.ID

	ORDER BY
		D,Salary DESC
	) as t
GROUP BY
	D
;

原创文章,作者:dweifng,如若转载,请注明出处:https://blog.ytso.com/277620.html

(0)
上一篇 2022年7月28日
下一篇 2022年7月28日

相关推荐

发表回复

登录后才能评论