代码之家  ›  专栏  ›  技术社区  ›  user3724032

在MySQL中查找与每个订单大小相关的订单数

  •  -1
  • user3724032  · 技术社区  · 6 年前

    需要一些MySQL查询的帮助才能在更大的数据库中使用。在这里,我需要找到与每个订单大小相关的订单数量。

    我一直在尝试让查询使用很多组合,比如:COUNT(DISTINCT item)或GROUP\u CONCAT(DISTINCT order\u id)、GROUP BYs、order BYs、HAVING COUNT(DISTINCT item\u id)等,但结果并不是我真的需要它。任何帮助我朝着正确的方向前进都将不胜感激。

    表名为:items

    item_id    order_id    item
    -------------------------------
    1          1           apple
    2          1           orange
    3          1           grape
    4          2           grape
    5          3           apple
    6          3           orange
    7          4           apple
    8          5           orange
    9          5           apple
    10         6           apple
    11         6           orange
    12         6           grape
    13         7           orange
    14         8           grape
    

    在本例中,查询结果为:

    Number_of_Orders        Total_Order_Size
    ----------------------------------------
    4                       1
    2                       2
    2                       3
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Vamsi Prabhala    6 年前

    你必须这样 group by 两次。

    select item_count,count(*)
    from (select order_id,count(*) as item_count
          from tbl 
          group by order_id
         ) t
    group by item_count
    
        2
  •  0
  •   Gordon Linoff    6 年前

    可以使用两个聚合级别:

    select num_items, count(*) as num_orders
    from (select order_id, count(*) as num_items
          from t
          group by order_id
         ) o
    group by num_items
    order by num_items;