【问题标题】:MYSQL group by when greater than XMYSQL group by 当大于 X
【发布时间】:2020-04-05 19:19:09
【问题描述】:

让我解释一下我的问题。
在 mysql 中,我有一个这样的订单表(简化):

+------------+-------+
| customerID | price | 
+------------+-------+
| 10         | 10    |
| 20         | 10    |
| 20         | 10    |
| 30         | 10    |
| 30         | 10    |
| 30         | 10    |
| 120        | 10    |
| 120        | 10    |
| 130        | 10    |
| 130        | 10    |
| 130        | 10    |
| 130        | 10    |
+------------+-------+

我想要总价的订单数量的客户数量。

+-----------------------------+--------------------+-------------+  
| number_of_order_by_customer | number_of_customer | total_price |  
+-----------------------------+--------------------+-------------+  
| 1                           | 1                  | 10          |  
| 2                           | 2                  | 40          |  
| 3 and more                  | 2                  | 70          |  
+-----------------------------+--------------------+-------------+  

我们可以像这样阅读这张表:
- 1 位客户以 10 欧元订购了 1 次(客户 10)
- 2 位客户订购了 2 次,共计 40 欧元(客户 20 和客户 120)
- 2 位客户订购 3 次或更多,总计 70 欧元(客户 30(3 次)和客户 130(4 次))

我的问题是“3 和更多” 有了这个请求,我可以有 1、2、3、4 次,但我不知道如何分组 3 和 4 次

SELECT 
    number_of_order_by_customer, COUNT(number_of_order_by_customer) AS number_of_customer, SUM(price) AS total_price 
FROM
(
    SELECT
        COUNT(o.customerID ) AS number_of_order_by_customer, sum(o.price ) AS price
    FROM 
        order o
    GROUP BY o.customerID 
) AS tmp

GROUP BY number_of_order_by_customer
;

我明白了:

+-----------------------------+--------------------+-------------+  
| number_of_order_by_customer | number_of_customer | total_price |  
+-----------------------------+--------------------+-------------+  
| 1                           | 1                  | 10          |  
| 2                           | 2                  | 40          |  
| 3                           | 1                  | 30          |  
| 4                           | 1                  | 40          |
+-----------------------------+--------------------+-------------+  

有谁知道如何在同一个请求中获得“3 个或更多”?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    表达式时的用例-

    SELECT 
        case when number_of_order_by_customer>=3 then '3 or More' else cast(number_of_order_by_customer as varchar(10)) end as number_of_order_by_customer, COUNT(nb) AS number_of_customer, SUM(price) AS total_price 
    FROM
    (
        SELECT
            COUNT(o.customerID ) AS number_of_order_by_customer, sum(o.price ) AS price
        FROM 
            order o
        GROUP BY o.customerID 
    ) AS tmp
    
    GROUP BY case when number_of_order_by_customer>=3 then '3 or More' else cast(number_of_order_by_customer as varchar(10)) end
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多