练习一: 各部门工资最高的员工

题目描述

创建Employee 表,包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id,如下所示

  1. +----+-------+--------+--------------+
  2. | Id | Name | Salary | DepartmentId |
  3. +----+-------+--------+--------------+
  4. | 1 | Joe | 70000 | 1 |
  5. | 2 | Henry | 80000 | 2 |
  6. | 3 | Sam | 60000 | 2 |
  7. | 4 | Max | 90000 | 1 |
  8. +----+-------+--------+--------------+

创建Department 表,包含公司所有部门的信息,如下所示

  1. +----+----------+
  2. | Id | Name |
  3. +----+----------+
  4. | 1 | IT |
  5. | 2 | Sales |
  6. +----+----------+

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

  1. +------------+----------+--------+
  2. | Department | Employee | Salary |
  3. +------------+----------+--------+
  4. | IT | Max | 90000 |
  5. | Sales | Henry | 80000 |
  6. +------------+----------+--------+

答案

首先创建表Employee

  1. create table Employee(Id integer,Name varchar(10),Salary integer,DepartmentId integer);

向其中插入数据

  1. insert into Employee values (1,'Joe',70000,1),
  2. (2,'Henry',80000,2),
  3. (3,'Sam',60000,2),
  4. (4,'Max',90000,1);

接下来,创建表Department

  1. create table Department(ID integer,Name varchar(10))

往其中插入数据

  1. insert into Department values(1,'IT'),(2,'Sales')

接下来进行查询,这道题和Task03关联子查询是一样的

  1. select Employer,Salary,DepartmentId
  2. from Employee as Emp1
  3. where Salary =
  4. (select max(Salary)
  5. from Employee as Emp2
  6. where Emp1.DepartmentId= Emp2.DepartmentId
  7. group by DepartmentId)

查询后,如下所示
image.png

练习二: 换座位(难度:中等)

题目描述

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id,其中纵列的id是连续递增的

小美想改变相邻俩学生的座位,你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

请创建如下所示seat表:

  1. +---------+---------+
  2. | id | student |
  3. +---------+---------+
  4. | 1 | Abbot |
  5. | 2 | Doris |
  6. | 3 | Emerson |
  7. | 4 | Green |
  8. | 5 | Jeames |
  9. +---------+---------+

假如数据输入的是上表,则输出结果如下:

  1. +---------+---------+
  2. | id | student |
  3. +---------+---------+
  4. | 1 | Doris |
  5. | 2 | Abbot |
  6. | 3 | Green |
  7. | 4 | Emerson |
  8. | 5 | Jeames |
  9. +---------+---------+

注意: 如果学生人数是奇数,则不需要改变最后一个同学的座位。

答案

先插入数据

  1. create table seat(id integer,student varchar(10))
  2. insert into seat values (1,'Abbot'),(2,'Doris'),(3,'Emerson'),(4,'Green'),(5,'Jeames')

接下来交换位置

  1. CREATE PROCEDURE test()
  2. # 查询行数
  3. set @cnt = (select count(*) from Employee);
  4. select @cnt;
  5. #开始循环
  6. BEGIN
  7. DECLARE i INT DEFAULT 0;
  8. WHILE i<40 DO
  9. if
  10. INSERT INTO authors(authName) VALUES ();
  11. SET i=i+1;
  12. END WHILE;
  13. END

练习四:连续出现的数字(难度:中等)

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

  1. +----+-----+
  2. | Id | Num |
  3. +----+-----+
  4. | 1 | 1 |
  5. | 2 | 1 |
  6. | 3 | 1 |
  7. | 4 | 2 |
  8. | 5 | 1 |
  9. | 6 | 2 |
  10. | 7 | 2 |
  11. +----+-----+

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

首先,插入数据

  1. create table table3(Id integer,Num integer);
  2. insert into table3 values(1,1),(2,1),(3,1),(4,2),(5,1),(6,2),(7,2);

查询