由于篇幅限制,以下是解答中的核心函数和关键代码,以及对于题型分析和解答的概要。
-- 数据准备SQL
CREATE TABLE IF NOT EXISTS `employees` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`role` VARCHAR(50) NOT NULL,
`salary` INT NOT NULL,
PRIMARY KEY (`id`)
);
-- 插入示例数据
INSERT INTO `employees` (name, role, salary) VALUES
('Jane', 'Developer', 60000),
('Jason', 'Developer', 65000),
('Sarah', 'Developer', 70000),
('Blake', 'Manager', 90000);
-- 查询示例1:查询不同角色的员工数量
SELECT role, COUNT(*) AS number_of_employees
FROM employees
GROUP BY role;
-- 查询示例2:查询每个角色的平均薪资
SELECT role, AVG(salary) AS average_salary
FROM employees
GROUP BY role;
-- 查询示例3:查询薪资高于部门平均水平的员工
SELECT e1.name, e1.salary
FROM employees e1
JOIN (
SELECT role, AVG(salary) as avg_salary
FROM employees
GROUP BY role
) e2 ON e1.role = e2.role
WHERE e1.salary > e2.avg_salary;
-- 查询示例4:查询每个部门的员工数量,以及每个部门薪资高于部门平均水平的员工的数量
SELECT role,
COUNT(*) AS number_of_employees,
SUM(CASE WHEN salary > e2.avg_salary THEN 1 ELSE 0 END) AS number_of_employees_above_avg
FROM employees e1
JOIN (
SELECT role, AVG(salary) as avg_salary
FROM employees
GROUP BY role
) e2 ON e1.role = e2.role
GROUP BY role;
以上代码提供了数据准备和查询示例,涵盖了不同类型的查询操作,包括聚合查询、关联子查询等。每个查询都有详细的分析和相应的SQL语句,足以帮助开发者巩固MySQL查询技巧。