让我解释一下我的问题。
在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次,每次10欧元(客户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个及更多”吗?
答案 0 :(得分:0)
表达时的用例-
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