1. 获取每个部门薪资最高的员工信息
题目:在 Employees
表中,获取每个部门(department
)薪资最高的员工的姓名、部门和工资。表结构如下:
id
(INT)name
(VARCHAR)department
(VARCHAR)salary
(DECIMAL)
答案示例:
代码语言:javascript复制SELECT e.name, e.department, e.salary
FROM Employees e
WHERE e.salary = (
SELECT MAX(salary)
FROM Employees
WHERE department = e.department
);
2. 查找连续登录3天的用户
题目:在 UserLogins
表中,包含以下字段:
user_id
(INT)login_date
(DATE)
请查询连续登录3天以上的所有用户ID。
答案示例:
代码语言:javascript复制SELECT DISTINCT a.user_id
FROM UserLogins a, UserLogins b, UserLogins c
WHERE a.user_id = b.user_id
AND b.user_id = c.user_id
AND DATEDIFF(b.login_date, a.login_date) = 1
AND DATEDIFF(c.login_date, b.login_date) = 1;
(或者可以使用窗口函数,视数据库支持情况而定)
3. 获取累计工资排名
题目:在 Employees
表中,计算每个员工的工资排名,并按工资从高到低进行排序。表结构如下:
id
(INT)name
(VARCHAR)salary
(DECIMAL)
答案示例:
代码语言:javascript复制SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM Employees;
4. 查找前N个最高薪资的员工
题目:获取 Employees
表中第N高工资的员工信息(N是变量),要求能够灵活查询不同N值的结果。
答案示例:
代码语言:javascript复制SELECT name, salary
FROM (
SELECT name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM Employees
) AS ranked
WHERE salary_rank = N;
5. 查找没有关联数据的记录
题目:有两张表 Employees
和 Projects
。Projects
表结构:
id
(INT)employee_id
(INT)
请查询没有参与任何项目的员工。
答案示例:
代码语言:javascript复制SELECT e.name
FROM Employees e
LEFT JOIN Projects p ON e.id = p.employee_id
WHERE p.employee_id IS NULL;
6. 使用递归查询获取员工层级
题目:在 Employees
表中,每个员工都有一个 manager_id
,表示其直属经理。请编写SQL语句以递归方式查找一个特定员工的所有上级。
Employees
表结构如下:
id
(INT)name
(VARCHAR)manager_id
(INT)
答案示例:
代码语言:javascript复制WITH RECURSIVE EmployeeHierarchy AS (
SELECT id, name, manager_id
FROM Employees
WHERE id = :employee_id -- 替换为指定员工ID
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM Employees e
JOIN EmployeeHierarchy eh ON e.id = eh.manager_id
)
SELECT * FROM EmployeeHierarchy;
7. 计算每月的累计销售额
题目:在 Sales
表中,包含以下字段:
sale_id
(INT)sale_date
(DATE)amount
(DECIMAL)
请计算每个月的累计销售额。
答案示例:
代码语言:javascript复制SELECT DATE_FORMAT(sale_date, '%Y-%m') AS month,
SUM(amount) OVER (ORDER BY DATE_FORMAT(sale_date, '%Y-%m')) AS cumulative_sales
FROM Sales;
8. 查询每个部门中工资比平均工资高的员工
题目:在 Employees
表中,查询每个部门中工资比该部门平均工资高的员工姓名和工资。
答案示例:
代码语言:javascript复制SELECT name, department, salary
FROM Employees e
WHERE salary > (
SELECT AVG(salary)
FROM Employees
WHERE department = e.department
);
9. 多条件分组的复杂统计
题目:在 Orders
表中,包含以下字段:
order_id
(INT)order_date
(DATE)customer_id
(INT)amount
(DECIMAL)
请统计每年每月的订单数量和总金额。
答案示例:
代码语言:javascript复制SELECT YEAR(order_date) AS year, MONTH(order_date) AS month,
COUNT(order_id) AS total_orders,
SUM(amount) AS total_amount
FROM Orders
GROUP BY YEAR(order_date), MONTH(order_date);
10. 查找重复数据
题目:在 Employees
表中,查询姓名和年龄都相同的员工的数量(重复数据)。
答案示例:
代码语言:javascript复制SELECT name, age, COUNT(*) AS num_duplicates
FROM Employees
GROUP BY name, age
HAVING COUNT(*) > 1;