Find Customers who have purchased more than 2 times. Get the
1. customer information
2. purchase frequency
3. total spending
4. avg basket size.
我已经得到了1 - 3,但我对4号做不了多少。 产品上的值可以有多个值,以逗号分隔。
〜> (产品编号:12,4,5) - >如果订单购买超过1个产品
我到了可以将它与长度替换分开的地步,但我对如何将其显示为平均篮子大小感到困惑。
感谢您的帮助!
SQL表格图像 sql table
**Customer**
Customer ID
Name
AddressCity
**Order**
OrderID
CustomerID
ProductID
Total
**Delivery**
DeliveryID
OrderID
AddressCity
这是我当前的sql语句
SELECT Customer.*, Order.CustomerID,
COUNT(Order.CustomerID) AS PurchaseFrequency,
SUM(Order.Total) AS TotalSpending
FROM Customer JOIN Order
ON Customer.CustomerID=Order.CustomerID
Group By Customer.CustomerID
Having Count(*) > 1
答案 0 :(得分:1)
LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1
应该为您提供每个订单的总产品数量。 只需将其添加到现有语句中即可。
SELECT Customer.*, Order.CustomerID,
COUNT(Order.CustomerID) AS PurchaseFrequency,
SUM(Order.Total) AS TotalSpending,
AVG(LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1) as AvgProdQuantityPerOrder
FROM Customer JOIN Order
ON Customer.CustomerID=Order.CustomerID
Group By Customer.CustomerID
Having Count(*) > 1
修改强>
SELECT部分中使用的字段也应在GROUP BY部分中指定。您的查询将变为如此:
SELECT Customer.CustomerID, Customer.Name, Customer.AdressCity,
COUNT(Order.CustomerID) AS PurchaseFrequency,
SUM(Order.Total) AS TotalSpending,
AVG(LEN(Order.ProductID) - LEN(REPLACE(Order.ProductID, ',', '')) + 1) as AvgProdQuantityPerOrder
FROM Customer JOIN
Order ON Customer.CustomerID=Order.CustomerID
GROUP BY Customer.CustomerID, Customer.Name, Customer.AdressCity
Having Count(*) > 1