SQL, W3school 练习题 - 找出法国客户订购最多的产品

SQL, W3school practice problem - find the product that was ordered most with by customers in France

在 W3school 上做一道练习题 - 数据库是 here: https://www.w3schools.com/SQL/TRYSQL.ASP?FILENAME=TRYSQL_SELECT_ALL

我正在尝试 return 法国国家(Country 中客户订购最多的产品(在 table OrderDetails 中找到)在 table Customers 中)。为此,我首先必须加入 3 个 table:首先在 OrderID 上加入 OrderDetailsOrders,然后加入合并后的 table 和 CustomersCustomerID 上。问题是,既然我有了 table,我似乎无法弄清楚如何 return 法国客户订购最多的 ProductID。以下代码:

SELECT
    c.customer_id,
    SUM(od.Quantity) AS totalQuantity
    FROM (OrderDetails od LEFT JOIN Orders o ON od.OrderID = o.OrderID)
    LEFT JOIN Customers c ON o.CustomerID = c.CustomerID
    GROUP BY od.ProductID
    ORDER BY totalQuantity DESC
    LIMIT 1;

returns 错误:

Syntax error in ORDER BY clause

对我在这里做错了什么有什么建议吗?我正在做的事情是否接近 return 法国客户订购最多的 ProductID?

LIMIT 不是 Access SQL 语法,所以请尝试:

SELECT TOP 1
    od.ProductID,
    SUM(od.Quantity) AS totalQuantity
FROM 
    (OrderDetails AS od 
LEFT JOIN 
    Orders AS o ON od.OrderID = o.OrderID)
LEFT JOIN 
    Customers AS c ON o.CustomerID = c.CustomerID
GROUP BY 
    od.ProductID
ORDER BY 
    SUM(od.Quantity) DESC;

W3Schools 正在使用连接到 SqLite 3 的 WebSQL

您可以查看它的版本:

SELECT sqlite_version();

问题中的查询不起作用,因为它选择了 c.customer_id,应该是 c.CustomerID

此查询将 return 法国拥有最多独特客户的产品。

国家取自客户table。
Products table 仅加入以获取产品名称。

SELECT 
  od.ProductID
, p.ProductName
, COUNT(DISTINCT o.OrderID) AS TotalOrders
, COUNT(DISTINCT c.CustomerID) AS TotalCustomers
, SUM(od.Quantity) AS TotalQuantity
FROM "OrderDetails" AS od
INNER JOIN "Orders" AS o ON o.OrderID = od.OrderID
INNER JOIN "Customers" AS c ON c.CustomerID = o.CustomerID
INNER JOIN "Products" AS p ON p.ProductID = od.ProductID
WHERE c.Country = 'France' 
GROUP BY od.ProductID, p.ProductName
ORDER BY TotalCustomers DESC
LIMIT 1

这是肉馅饼。

你是这个意思吗?

SELECT
c.CustomerID, c.Country,
SUM(od.Quantity) AS totalQuantity
FROM Customers c
LEFT JOIN Orders o ON (c.CustomerID = o.CustomerID)
LEFT JOIN OrderDetails od ON (od.OrderID = o.OrderID)
where c.Country = 'France'
GROUP BY c.CustomerID, c.Country
ORDER BY totalQuantity DESC;

这将输出法国客户的订单数量