SQL按重复行降序排序

SQL按重复行降序排序,sql,oracle,duplicates,sql-order-by,Sql,Oracle,Duplicates,Sql Order By,我的表格如下所示: cust_ref|account_num 123456 | 001132 321234 | 123213 325123 | 412312 123456 | 312321 我基本上要做的是将重复的cust_ref行排序在一起,并对其排序,以便所有重复项都从第1行开始按降序排列。i、 e如果有一个客户参考号对应于3个客户编号,那么它将位于对应于2个客户编号的客户参考号的更高一行 e、 g cust_ref|account_num 123456 |

我的表格如下所示:

cust_ref|account_num
123456  |     001132  
321234   | 123213  
325123 | 412312  
123456 | 312321 
我基本上要做的是将重复的cust_ref行排序在一起,并对其排序,以便所有重复项都从第1行开始按降序排列。i、 e如果有一个客户参考号对应于3个客户编号,那么它将位于对应于2个客户编号的客户参考号的更高一行

e、 g

cust_ref|account_num
123456  |     001132  
123456 | 312321   
321234   | 123213  
325123 | 412312  
我目前的查询是:

select cust_ref,  
       account_num  
from (
  select cust_ref,  
         account_num,  
         max(phone_num)  
   from table_name  
   group by cust_ref,  account_num
)  

如果您的RDBMS支持
窗口函数(分析函数)
,那么您可以使用:

SELECT 
    SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
    cust_ref, account_num, 
    MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY 1 DESC, 2, 3;    --cnt DESC, cust_ref, account_num
SELECT 
    SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
    COUNT(*) AS cnt_in_group,
    cust_ref, account_num, 
    MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY cnt DESC, cnt_in_group DESC, cust_ref, account_num;   
测试

如果您想在每组
cust\u ref、account\u num
中订购,请使用以下命令:

SELECT 
    SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
    cust_ref, account_num, 
    MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY 1 DESC, 2, 3;    --cnt DESC, cust_ref, account_num
SELECT 
    SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
    COUNT(*) AS cnt_in_group,
    cust_ref, account_num, 
    MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY cnt DESC, cnt_in_group DESC, cust_ref, account_num;   

Link

Pham的答案比这个好,但是,如果你想老生常谈,像这样的方法应该行得通

declare  @cust_accts table 
( 
   cust_ref  int NOT NULL, 
   account_num int not null
)

insert into @cust_accts values (123456 , 001132)
insert into @cust_accts values (321234 , 123213)
insert into @cust_accts values (325123 , 412312)
insert into @cust_accts values (123456 , 312321)

select a.cust_ref, 
       a.account_num,
       b.acct_cnt
from   @cust_accts  a
join   
(
    select cust_ref, count(*) as acct_cnt
    from   @cust_accts
    group  by cust_ref
) b
on a.cust_ref = b.cust_ref
order by b.acct_cnt, a.cust_ref, a.account_num
我不知道为什么我的回答节目比范的高,他的要优雅得多。

你似乎想要:

select cust_ref, account_num
from t
order by count(*) over (partition by cust_ref) desc,
         cust_ref,
         account_num;
您也可以将计数包含在所需的结果中,但示例结果仅包含两个指定的列


如果您的数据库不支持窗口功能,您也可以在那里使用子查询。

您的RDBMS是什么?Oracle,MSSQL,mysql,PostgreSql。。。?请添加您的RDBMS标签。抱歉,第一次发布。这看起来正是我需要的,非常感谢!当您的DBMS不支持
窗口/分析函数时,这个想法很好