【问题标题】:SQL order by duplicate rows descendingSQL 按重复行降序排列
【发布时间】:2019-07-18 10:08:42
【问题描述】:

我的桌子看起来像:

cust_ref | account_num  
123456  |     001132  
321234   | 123213  
325123 | 412312  
123456 | 312321 

我基本上要做的是将重复的 cust_ref 行排序在一起并对其进行排序,以便所有重复项从第 1 行开始按降序排列。即,如果有一个对应于 3 个 account_num 的 cust_ref 编号,那么它将位于对应于 2 个 account_num 的 cust_ref 的较高行

例如

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?甲骨文、MSSQL、mysql、PostgreSql……?请添加您的 RDBMS 的标签。

标签: sql oracle duplicates sql-order-by


【解决方案1】:

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

不知道为什么我的答案显示在 Pham 之上,他的更优雅。

【讨论】:

  • 当你的 DBMS 不支持window/ analytic functions时,这个想法很好
【解决方案2】:

如果您的 RDBMS 支持window functions (analytic functions),那么您可以使用这个:

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

rextester for Oracle 测试

如果您也想在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;   

链接rextester

【讨论】:

  • 抱歉,第一次发帖。这看起来正是我所需要的,非常感谢!
【解决方案3】:

你似乎想要:

select cust_ref, account_num
from t
order by count(*) over (partition by cust_ref) desc,
         cust_ref,
         account_num;

您也可以在所需结果中包含计数,但您的示例结果仅包含指定的两个列。

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

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多