[英]Aggregating column values based on range
我是 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
這是不正確的(甚至不工作)。
您可以使用:
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);
如果客戶在給定組中進行了多次購買,則不清楚您是要計算購買次數還是要計算客戶數量。 這兩者都有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.