MySQL(三)

练习1:找出各部门工资最高的员工
题目要求:
在这里插入图片描述
思路:
首先依据要求将两个表格进行组合成一个表格,再加入一个表格(依据部门进行分组且取个部门最大薪水)组合显示
1—两个表格的创建及数据载入

create table employee(

id int unsigned primary key not null auto_increment,
name varchar(20) not null,
salary int unsigned,
departmentid int unsigned



);

insert into employee values(1,"Joe",70000,1);
insert into employee values(2,"Henry",80000,2);
insert into employee values(3,"Sam",60000,2);
insert into employee values(4,"Max",90000,1);

create table department(

id int unsigned primary key not null,
name varchar(20) not null

);

insert into department values(1,"IT");
insert into department values(2,"Sales");

2—操作

select a.* from (select department.name as department,employee.name,employee.salary from employee,department  where employee.departmentid=department.id) as a
join(
select max(salary) as salary from employee group by departmentid) as g where a.salary=g.salary ;

3—效果展示
在这里插入图片描述

练习2:换座位,交换相邻两项顺序,末位为奇数为则不进行交换
题目要求:
在这里插入图片描述
思路:
按照id的奇数偶数性进行分类处理,若为奇数且不是末位奇数,则id值加1,是末位奇数则不变id值,若为偶数id,则id值减1。
1—表格创建及插入数值

create table seat(

id int unsigned primary key not null auto_increment,
student varchar(255) not null 



);
insert into seat values(1,"Abbot"),(2,"Doris"),(3,"Emerson"),(4,"Green"),(5,"Jeames");
select * from seat;

2—操作

select id+1 as id,student from seat where id mod 2=1 and id <> (select count(*) from seat)
select id,student from seat where id mod 2=1 and id=(select count(*) from seat)
select id-1,student from seat where id mod 2=0

联合

(select id+1 as id,student from seat where id mod 2=1 and id <> (select count(*) from seat) union select id,student from seat where id mod 2=1 and id=(select count(*) from seat) union select id-1,student from seat where id mod 2=0) as a

实现

select * from (select id+1 as id,student from seat where id mod 2=1 and id <> (select count(*) from seat) union select id,student from seat where id mod 2=1 and id=(select count(*) from seat) union select id-1,student from seat where id mod 2=0) as a order by a.id;

3—效果展示
在这里插入图片描述
练习3:分数排名,且名次之间无“间隔”
题目要求:
在这里插入图片描述
1—表格的创建及数据插入

create table score(

id int unsigned not null primary key auto_increment,

score decimal(3,2)


);

insert into score values(1,3.50),(2,3.65),(3,4.00),(4,3.85),(5,4.00),(6,3.65);
select * from score;

2—操作

select dense_rank() over (order by score desc) as rank1,score from score;

3—效果展示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值