基于范围聚合列值

8i9zcol2  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(249)

我是sql和stackoverflow的新手,如果我的问题很琐碎,请原谅。我在一个表中记录了客户的购买量,所以我想统计一下购买量在某个范围内的客户。

TABLE:
+-------------+----------------+
| customer_id | order_quantity |
+-------------+----------------+
|         123 |          10000 |
|         143 |           5000 |
|         999 |         200000 |
|         555 |          50000 |
+-------------+----------------+

我们的目标是统计有多少客户购买了<5000,订单数量介于5000-50000和50000-100000之间。
我用过:

SELECT customer_id,
      CASE
         WHEN COUNT(order_quantity) < 5000
         ....
FROM purchases

这是不正确的(甚至不工作)。

velaa5lx

velaa5lx1#

您可以使用:

select (case when order_quantity < 5000 then '[0-5000)'
             when order_quantity < 10000 then '[5000-10000)'
             else '10000+'
        end) as grp,
       count(*) as num_purchases,
       count(distinct customer_id) as num_customers
from t
group by grp
order by min(order_quantity);

如果客户在给定的组中进行了多个购买,则不清楚您是要计算购买数量还是要计算客户数量。这两者兼而有之。

相关问题