sql如何取group by 分组的多条记录只取最上面的一条!

2025-01-05 22:16:24
推荐回答(2个)
回答1:

1、创建测试表,create table test_order(userid varchar2(20), ranking varchar2(20), username varchar2(20));

2、插入样例数据,

insert into test_order values('001','C','aa');

insert into test_order values('001','B','bb');

insert into test_order values('002','A','cc');

3、查询表中所有记录,select t.*, rowid from test_order t;

4、编写sql,获取所需记录,

select *

  from (select t.*,

               row_number() over(partition by userid order by ranking desc) rn

          from test_order t)

 where rn = 1

回答2:

select userid,ranking,username from table
where userid+ranking in
(
select userid+max(ranking) from table
group by userid
)