之前@June第二题和第五题都可以使用mysql8 新功能窗口函数,试了一下,比较好理解。
相关SQL代码如下(含建表SQL)
第二题:
建表和数据SQL:
drop table if exists test1;
create table test1
(Id int primary key,
Name varchar(20),
Score decimal(4,2)
);
insert into test1 values(1,'张三',80);
insert into test1 values(2,'李四',90);
insert into test1 values(3,'王五',76);
insert into test1 values(4,'赵六',88);
insert into test1 values(5,'孙七',67);
查询SQL:
select * from (
SELECT
*
FROM
( SELECT rank() over ( ORDER BY Score DESC ) AS row_num, Id, NAME, Score FROM test1 ) t
WHERE
row_num =3
第五题:
drop table if exists student;
create table student
(
Id int primary key,
Stdname varchar(20),
Points decimal(4,2),
Classid tinyint
)
insert into student values(1,'张三',85,1);
insert into student values(2,'李四',80,2);
insert into student values(3,'王五',65,2);
insert into student values(4,'赵六',90,1);
insert into student values(5,'孙七',69,1);
insert into student values(6,'周八',85,1);
insert into student values(7,'郑九',70,1);
drop table if exists class;
create table class
(
Id int primary key,
Classname varchar(20)
)
insert into class values(1,'创新班');
insert into class values(2,'普通班');
查询SQL:
SELECT
Classname,
Stdname,
Points
FROM
(
SELECT
dense_rank() over ( PARTITION BY Classname ORDER BY Points DESC ) AS row_num,
Classname,
Stdname,
Points
FROM
student a
JOIN class b
WHERE
a.Classid = b.Id
) t
WHERE
row_num <= 3
第四题 可以用in很好写
SELECT id,teach.Fname from teach where id in (select Teacherid from teach GROUP BY Teacherid HAVING COUNT(Teacherid)> 2);
作者回复: 是的
zhuyuping
2022-04-22来自北京
第4题,这样写好像也可以?也是采用自连接
select t1.id, t1.fname
from demo.teach t1
left join demo.teach t2
on (t1.id = t2.teacherid)
group by t1.id having count(t1.id) >=2;