MYSQL group by 当大于 X
Posted
技术标签:
【中文标题】MYSQL group by 当大于 X【英文标题】:MYSQL group by when greater than 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 个或更多”?
【问题讨论】:
【参考方案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
【讨论】:
超级,但转换为 varchar 不起作用。将其转换为 char ***.com/a/15368838/12524340以上是关于MYSQL group by 当大于 X的主要内容,如果未能解决你的问题,请参考以下文章
Mysql报错注入原理分析(count()rand()group by)
Mysql报错注入原理分析(count()rand()group by)