我有一个表有两列 – 客户ID和他们购买的产品数量.
我会用什么sql语句来了解有多少客户购买了1个或更多产品,2个或更多产品,3个或更多产品等?
这可以在不使用交叉连接的情况下完成(我使用谷歌bigquery不支持).
最佳答案
如果您真的需要计算分别购买“一个或多个”和“两个或更多”的客户数量,您需要一个CASE表达式:
原文链接:https://www.f2er.com/mysql/433155.htmlSELECT SUM(CASE WHEN NumOfProducts >= 1 THEN 1 ELSE 0 END) AS Purchased_1_or_more,SUM(CASE WHEN NumOfProducts >= 2 THEN 1 ELSE 0 END) AS Purchased_2_or_more,SUM(CASE WHEN NumOfProducts >= 3 THEN 1 ELSE 0 END) AS Purchased_3_or_more,SUM(CASE WHEN NumOfProducts >= 4 THEN 1 ELSE 0 END) AS Purchased_4_or_more,SUM(CASE WHEN NumOfProducts >= 5 THEN 1 ELSE 0 END) AS Purchased_5_or_more
FROM Customers
等等,无论你想要多少类别.