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

时间:2016-11-10 17:44:41

标签: sql sql-server sql-order-by

如何根据主要排序方式订购第二列。让我们说......

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

返回

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

如何在数量分类后将客户分组?我希望数量是我的主要类别,客户是次要的。

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

谢谢!

编辑:在计数(*)

后忘记了desc

3 个答案:

答案 0 :(得分:1)

您可以使用此方法:

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

答案 1 :(得分:1)

Mister积极回答由于某种原因没有成功,但让我领先。 我使用了cte并添加了最大计数分区,它适用于我的意图

基于有问题的例子,cte会返回这样的内容。

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

对我来说感觉很脏但是这个现在可以用了。 谢谢大家。

答案 2 :(得分:0)

我还没有研究它的效率有多高,但窗口函数提供了解决这个问题的方法...

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

以下是创建和填充 Inventory 表的代码:

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)
;