我目前正在https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all使用数据集来学习SQL。
我给出的问题是“生成所有客户的列表以及他们所拥有的订单的总成本 - 尝试使用round()函数将总成本显示为2位小数。”
我正在输入代码:
SELECT c.CustomerName, ROUND(sum(CostPerCustomer),2) as "TotalCost"
FROM (
SELECT c.CustomerName, p.ProductName, (p.Price)*count(c.CustomerName)) AS "CostPerCustomer"
FROM Customers c, Products p, Orders o, OrderDetails od
WHERE c.CustomerID = o.CustomerID and p.ProductID = od.ProductID and o.OrderID = od.OrderID
GROUP BY c.CustomerName, p.ProductName
ORDER BY c.CustomerName, count(c.CustomerName) desc)
GROUP BY CustomerName
我收到错误消息'您试图执行不包含指定表达式'p.Price * count(c.CustomerName)'的查询作为聚合函数的一部分。'
是否有人能够告诉我我的代码有什么问题以及我如何修复它?
答案 0 :(得分:0)
你可以试试这个
SELECT CustomerName, round(sum(price*Quantity),2) AS TotalCost FROM Customers C
JOIN Orders O ON C.CustomerID = O.CustomerID
JOIN OrderDetails OD ON O.OrderID = OD.OrderID
JOIN Products P ON P.ProductID = OD.ProductID
GROUP BY CustomerName;
答案 1 :(得分:0)
这是一个如何连接多个表并解决问题的示例。 count(c.CustomerName)在这里不正确,你必须去订单表并获得属于客户的所有orderid,然后你去orderdetails表找到他们订购的产品和数量。然后,您转到产品表并获取每种产品的价格。
select c.customerid,c.customername,sum(p.price*od.quantity)
from customers c
join orders o on o.customerid=c.customerid
join orderdetails od on od.orderid=o.orderid
join products p on p.productid=od.productid
group by c.customerid,c.customername
order by c.customerid
答案 2 :(得分:0)
让我先纠正您当前的查询,使用适当的明确JOIN
s(即INNER JOIN
)
SELECT
c.CustomerName, ROUND(SUM(p.Price * od.Qty), 2) AS "TotalCostPerCustomer"
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
INNER JOIN Products p ON p.ProductID = od.ProductID
GROUP BY c.CustomerName