我试图通过编写查询以选择支出最高的前10名来确定客户的支出行为。
我有以下查询,它运行正常:
SELECT c.CustomerID
, SUM(Quantity * UnitPrice) Total_Spent
FROM Orders o
JOIN OrderDetails d
ON d.OrderID = o.OrderID
JOIN Customers c
ON c.CustomerID = o.CustomerID
GROUP
BY c.CustomerID
ORDER
BY Total_Spent
limit 10;
但是,我想创建一个子查询,而不要使用这个复杂的子查询。我已经尝试了以下方法,但是不起作用:
SELECT Customers.CustomerID
FROM Customers
JOIN (
SELECT SUM(Quantity *UnitPrice) as Total_Spent
FROM Orders
JOIN OrderDetails
ON Orders.OrderID = OrderDetails.OrderID) Orders
ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.CustomerID
ORDER BY Total_Spent
LIMIT 10;
我不知道问题是什么。 (我对SQL有点陌生)
答案 0 :(得分:1)
您可以简化查询,因为不需要customers
表。那和表别名应该使您的查询更简单:
SELECT o.CustomerID, SUM(od.Quantity * od.UnitPrice) as Total_Spent
FROM Orders o JOIN
OrderDetails od
ON o.OrderID = od.OrderID
GROUP BY o.CustomerID
ORDER BY Total_Spent DESC
LIMIT 10;