MySQL 实战

1. 各部门工资最高的员工

创建Employee 表与 Department 表如下所示,编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。

-- Employee 表
+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
+----+-------+--------+--------------+
-- Department 表
+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+
-- 查询结果
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

方案一:判断 e.Salary 是最大值

-- 查询每个部门工资最高的员工
SELECT
    d. NAME Department,
    e. NAME Employee,
    e.Salary
FROM
    Employee e
INNER JOIN Department d ON e.DepartmentId = d.ID
WHERE
    e.Salary = (
        SELECT
            MAX(Salary)
        FROM
            Employee e
        WHERE
            e.DepartmentID = d.ID
    );

 

方案二:对每个员工,先统计同部门工资大于他的有几个,这个方法可以筛选出每个部门工资前N高的人

-- 方案二
SET @limit_n = 1;  -- 定义变量,筛选各部门前N个工资最高的人

SELECT
    d. NAME Department,
    e. NAME Employee,
    e.Salary
FROM
    Employee e
INNER JOIN Department d ON e.DepartmentId = d.ID
WHERE
    (
        SELECT
            COUNT(1)
        FROM
            Employee e2
        WHERE
            e2.DepartmentID = d.ID
        AND e2.Salary > e.Salary
    ) < @limit_n;

 

2. 换座位

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。 其中纵列的 id 是连续递增的 小美想改变相邻俩学生的座位。 你能不能帮她写一个 SQL query 来输出小美想要的结果呢? (如果学生人数是奇数,则不需要改变最后一个同学的座位。)

-- 换座位前
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+
-- 换座位后
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

 

SELECT @cnt:=count(1) FROM seat;

SELECT 
    IF(id = @cnt, 
         id, 
         IF(MOD(id, 2)=1 , id+1, id-1)
  ) id,
    student
FROM seat 
ORDER BY id;

3. 分数排名

编写一个 SQL 查询来实现分数排名。如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

-- score 表
+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
-- 返回结果(按分数从高到低排列)
+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

 

SELECT
  s1.Score,
  (
    SELECT
      COUNT(DISTINCT Score)
    FROM
      Score s2
    WHERE
      s2.Score >= s1.Score
  ) Rank
FROM
  Score s1
ORDER BY
  s1.Score DESC;

 

posted @ 2019-03-03 19:40  只争朝夕0  阅读(172)  评论(0编辑  收藏  举报