gpt4 book ai didi

sql-server - 首先按最重复的记录排序

转载 作者:行者123 更新时间:2023-12-02 09:00:32 27 4
gpt4 key购买 nike

create table tbl_dup
(
name varchar(100)
);

insert into tbl_dup values('Arsel Rous'),('Oram Rock'),('Oram Rock'),('Brown Twor'),
('John Mak'),('Mak Dee'),('Smith Will'),('Mak Dee'),
('John Mak'),('Oram Rock'),('John Mak'),('Oram Rock');

查询:我正在寻找排序重复记录应显示在结果集中的第一级。

select * 
from
(
select name,row_number() over(partition by name order by name) rn
from tbl_dup
) a
order by name,rn;

获取:

name        rn
--------------
Arsel Rous 1
Brown Twor 1
John Mak 1
John Mak 2
John Mak 3
Mak Dee 1
Mak Dee 2
Oram Rock 1
Oram Rock 2
Oram Rock 3
Oram Rock 4
Smith Will 1

预期结果:

name        rn
---------------
Oram Rock 1
Oram Rock 2
Oram Rock 3
Oram Rock 4
John Mak 1
John Mak 2
John Mak 3
Mak Dee 1
Mak Dee 2
Arsel Rous 1
Brown Twor 1

最佳答案

尝试在 ORDER BY 子句中使用 COUNT 作为分析函数:

SELECT name, ROW_NUMBER() OVER (PARTITION by name ORDER BY name) rn
FROM tbl_dup
ORDER BY COUNT(*) OVER (PARTITION BY name) DESC, rn;

enter image description here

Demo

关于sql-server - 首先按最重复的记录排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977348/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com