SQL 服务器 - 找到最高计数后按组排序

SQL server - order by group after you find highest count

如何根据主要排序对第二列进行排序。让我们说...

select Customer, Status, count(*) as Qty
from Inventory
group by Customer, Status
order by count(*) desc

returns

Customer   |  Status  |  Qty
-------------------------------
102        |  2       |  500
101        |  1       |  400
102        |  1       |  300
101        |  2       |  200
102        |  3       |  100

数量排序后如何将客户分组?我希望 Qty 是我的主要排序,而 Customer 是次要的。

Customer   |  Status  |  Qty
-------------------------------
102        |  2       |  500
102        |  1       |  300
102        |  3       |  100
101        |  1       |  400
101        |  2       |  200

谢谢!

编辑:忘记计数后的 desc(*)

您可以使用这种方法:

Create Table #MyTempTable ( Customer int, MyStatus int, Qty Int)

Insert Into #MyTempTable
Select Customer, Status, count(*)
from Inventory
group by Customer, Status

Select * from #MyTempTable Order by Qty DESC, Customer

肯定先生的回答由于某种原因没有成功,但给了我领先。 我使用了 cte 并添加了最大计数分区,它符合我的意图

根据所讨论的示例,cte 会 return 像这样。

Customer   |  Status  |  Qty  |  mx
-------------------------------------
102        |  2       |  500  |  500
101        |  1       |  400  |  400
102        |  1       |  300  |  500
101        |  2       |  200  |  400
102        |  3       |  100  |  500

查询:

with cte as (
  select Customer
       , Status
       , count(*) as Qty
       , max(count(*)) over (partition by Customer) as mx
  from Inventory
  group by Customer, Status
)
select Customer, Status, Qty
from cte
order by mx desc, Qty desc

我觉得很脏,但这暂时有效。 谢谢大家

我还没有研究这有多有效,但是 window 函数提供了解决这个问题的方法...

SELECT    customer, status, COUNT(*)
FROM      Inventory AS I
GROUP BY  customer, status
ORDER BY  SUM(COUNT(*)) OVER(PARTITION BY customer) DESC,
          COUNT(*) DESC
;

这是创建和填充 Inventory table 的代码:

CREATE
TABLE   Inventory
(
  customer  int   not null,
  status    int   not null
);

INSERT
INTO    Inventory
VALUES  (101, 1), (101, 1), (101, 1), (101, 1),
        (101, 2), (101, 2),
        (102, 1), (102, 1), (102, 1),
        (102, 2), (102, 2), (102, 2), (102, 2), (102, 2),
        (102, 3)
;