📜  sql 查询面试题 githu - SQL (1)

📅  最后修改于: 2023-12-03 14:47:38.140000             🧑  作者: Mango

SQL查询面试题

SQL是关系型数据库管理系统中最常用的语言,因此在面试中也经常会考察SQL操作的能力。这里列举了一些常见的SQL查询面试题,希望能对程序员在面试中有所帮助。

题目1:查询每个部门的员工数量
SELECT
    department,
    COUNT(*) AS num_of_employees
FROM
    employee
GROUP BY
    department;

解释:使用聚合函数COUNT和GROUP BY子句,按照部门分组统计数量,输出每个部门的员工数量。

题目2:查询所有未下过订单的客户
SELECT
    *
FROM
    customer
WHERE
    NOT EXISTS (
        SELECT
            *
        FROM
            order
        WHERE
            customer.customer_id = order.customer_id);

解释:使用子查询和NOT EXISTS条件,筛选出未下过订单的客户,输出所有符合条件的客户信息。

题目3:查询每个部门平均工资最高的员工
SELECT
    department,
    MAX(salary) AS max_salary
FROM
    employee
GROUP BY
    department;

SELECT
    e.*
FROM
    employee e
    INNER JOIN (
        SELECT
            department,
            MAX(salary) AS max_salary
        FROM
            employee
        GROUP BY
            department
    ) m ON e.department = m.department AND e.salary = m.max_salary;

解释:首先使用第一个查询语句查询每个部门的平均工资最高值,然后使用INNER JOIN将结果与员工表连接,筛选出每个部门平均工资最高的员工。

题目4:查询每个部门的最高工资,以及领取该薪水的员工姓名
WITH cte_max_salary AS (
    SELECT
        department,
        MAX(salary) AS max_salary
    FROM
        employee
    GROUP BY
        department
)
SELECT
    e.department,
    e.name,
    cte_max_salary.max_salary
FROM
    employee e
    INNER JOIN cte_max_salary ON e.department = cte_max_salary.department AND e.salary = cte_max_salary.max_salary;

解释:使用CTE(Common Table Expression)语法,先查询每个部门的最高工资,然后利用INNER JOIN将结果与员工表连接,筛选出领取该薪水的员工姓名。

题目5:查询订单总数最多的前10个客户
SELECT
    customer.customer_id,
    customer.name,
    COUNT(*) AS num_of_orders
FROM
    order
    INNER JOIN customer ON order.customer_id = customer.customer_id
GROUP BY
    customer.customer_id,
    customer.name
ORDER BY
    num_of_orders DESC
LIMIT
    10;

解释:使用INNER JOIN将订单表和客户表连接,按照客户分组统计订单数量,使用ORDER BY DESC将结果倒序排列,使用LIMIT限制输出前10个结果。