【问题标题】:SQL server - order by group after you find highest countSQL Server - 找到最高计数后按组排序
【发布时间】:2016-11-10 17:44:40
【问题描述】:

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

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

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

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

谢谢!

编辑:count(*) 后忘记了 desc

【问题讨论】:

  • 您可以按多个字段排序。
  • @HunterMcMillen 问题是如果我执行“按数量排序(),客户”那么它什么都不做,因为数量优先。但是,如果我执行“按客户订购,计数()”,那么客户会按我想要的方式列出,但最高数量不会排在首位。我觉得我看到了一种订购和组合的方法,但我就是找不到。
  • order by count(*) desc 中尝试使用3 而不是count(*)
  • @Tek 我更新的答案对你有用。

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


【解决方案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

【讨论】:

    【解决方案2】:

    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
    

    对我来说感觉很脏,但这暂时可以。 谢谢大家。

    【讨论】:

    • 很高兴它有用@Tek
    • 您应该投票赞成任何有助于获得最终解决方案的答案@Tek。我应该想到CTE。 :-/
    • @MisterPositive 哈哈我想给你点赞,但我连15个声望都没有,哈哈
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多