1 说明
A表、B表两表关联,关联出来的结果里B表有不止一条,需求是只要B表结果中的某一条(按某字段排序);
首先想到了直接写个带排序的子查询去匹配外围的值,从这个结果集中只要第一条,但是经过验证发现,里边的条件是获取不到外层的值的,因此此方案不可行;
发现 row_number() over函数可用,以下是数据环境及结果。
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;
--单表的示例 --一条数据有多条日志记录,结果集只取最新的一条 select fi.col1, fi.col2, fi.col3 from (select t.col1, t.col2, t.col3, row_number() over(partition by t.col3 order by t.col2 desc) rw from t where 1 = 1 and to_char(t.col2, 'yyyy-mm-dd') >= '2024-09-01' and to_char(t.col2, 'yyyy-mm-dd') <= '2024-09-21') fi where fi.rw = 1 and to_char(col2, 'yyyy-mm-dd') >= '2024-09-01' and to_char(col2, 'yyyy-mm-dd') <= '2024-09-21' order by col2 desc
原文链接:https://blog.csdn.net/weixin_42256765/article/details/107640602
标签:insert,varchar,两表,只取,col2,values,Oracle,into,select From: https://www.cnblogs.com/daytoy105/p/18435864