练习一: 各部门工资最高的员工
题目描述
创建Employee 表,包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id,如下所示
+----+-------+--------+--------------+
| 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 |
+----+----------+
编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
答案
首先创建表Employee
create table Employee(Id integer,Name varchar(10),Salary integer,DepartmentId integer);
向其中插入数据
insert into Employee values (1,'Joe',70000,1),
(2,'Henry',80000,2),
(3,'Sam',60000,2),
(4,'Max',90000,1);
接下来,创建表Department
create table Department(ID integer,Name varchar(10))
往其中插入数据
insert into Department values(1,'IT'),(2,'Sales')
接下来进行查询,这道题和Task03关联子查询是一样的
select Employer,Salary,DepartmentId
from Employee as Emp1
where Salary =
(select max(Salary)
from Employee as Emp2
where Emp1.DepartmentId= Emp2.DepartmentId
group by DepartmentId)
练习二: 换座位(难度:中等)
题目描述
小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id,其中纵列的id是连续递增的
小美想改变相邻俩学生的座位,你能不能帮她写一个 SQL query 来输出小美想要的结果呢?
请创建如下所示seat表:
+---------+---------+
| id | student |
+---------+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+---------+---------+
假如数据输入的是上表,则输出结果如下:
+---------+---------+
| id | student |
+---------+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+---------+---------+
注意: 如果学生人数是奇数,则不需要改变最后一个同学的座位。
答案
先插入数据
create table seat(id integer,student varchar(10))
insert into seat values (1,'Abbot'),(2,'Doris'),(3,'Emerson'),(4,'Green'),(5,'Jeames')
接下来交换位置
CREATE PROCEDURE test()
# 查询行数
set @cnt = (select count(*) from Employee);
select @cnt;
#开始循环
BEGIN
DECLARE i INT DEFAULT 0;
WHILE i<40 DO
if
INSERT INTO authors(authName) VALUES ();
SET i=i+1;
END WHILE;
END
练习四:连续出现的数字(难度:中等)
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。
首先,插入数据
create table table3(Id integer,Num integer);
insert into table3 values(1,1),(2,1),(3,1),(4,2),(5,1),(6,2),(7,2);
查询