背景:
A表、B表两表关联,关联出来的结果里B表有不止一条,需求是只要B表结果中的某一条(按某字段排序)
经过百度,发现 row_number() over(partition by a order by b desc)函数可用(需要说明下,order by 必须有缺少会报错),以下是数据环境及结果。
创建数据环境
create table A(ANAME varchar(20));
insert into A values('alan');
insert into A values('Alee');
insert into A values('aspn');
create table B
(
BNo varchar(10),
BTell varchar(20),
Name varchar(20)
);
insert into B values('NO1','1366666','alan');
insert into B values('NO1','1388888','alan');
insert into B values('NO1','1399999','alan');
insert into B values('NO2','1333333','Alee');
insert into B values('NO3','1311111','aspn');
insert into B values('NO3','1322222','aspn');
直接关联查询的话,结果如下
需求是只要每个人的第一条记录(按BTELL排序)
select *
from a
left join (select *
from (select b. *,
(row_number()
over(partition by bno order by BTell desc)) px
from b) e
where px = 1) t
on a.aname = t.name;
查询结果如下